上传前jQuery-File-Upload重命名文件

时间:2015-06-17 12:54:58

标签: javascript jquery ruby-on-rails ruby amazon-s3

我正在使用lib jQuery-File-Upload在我的aws s3存储桶上传文件。 我的问题是我想在上传之前重命名我的文件,因为如果文件名上有特殊字符,aws返回的url不正确,我无法在控制器rails中打开它。

有没有办法覆盖lib中的一个函数来重命名文件?

谢谢,

2 个答案:

答案 0 :(得分:2)

在遵循Heroku教程后,我遇到了类似的挑战。我想从文件名中删除空格,并根据当前项目添加文件夹前缀。为了在上传到S3之前更改文件名,我添加了submit callback,我在客户端修改了名称。

fileInput.fileupload({
    ...
    submit: function (e, data) {
        // Get the original filename
        var fileName = data.originalFiles[0].name
        // Get the prefix from the form 
        var keyPrefix = form.data('key-start')
        // Combine the prefix and the original filename with start/end whitespace removed
        var fullFileName = keyPrefix + fileName.trim();
        // Replace whitespaces with underscores
        // At this step you could replace other special characters as well
        var newFileName = fullFileName.replace(/\s+/g, '_');
        // Update the form data with the new key value
        $(form.data('form-data')).attr("key", newFileName);
        // Set the form data
        data.formData = form.data('form-data');
    },
    ...
});

由于我更改了文件名,我需要确保S3也知道。教程建议控制器key方法中的set_s3_direct_post值为:

key: "uploads/#{SecureRandom.uuid}/${filename}"

key方法要求文件名与创建帖子网址时提供的文件名相匹配(因为我没有使用动态${filename}值,因此我不会这样做在创建直接发布URL以指定它时,不知道最终文件名。我使用key_starts_with方法,以便我可以指定项目文件夹前缀(删除空格),S3只会评估匹配项:

key_starts_with: "#{(current_project.name).strip.split(' ').join('_')}/"

我的最终set_s3_direct_post方法是:

def set_s3_direct_post
    @s3_direct_post = S3_BUCKET.presigned_post(key_starts_with: "#{(current_project.name).strip.split(' ').join('_')}/", success_action_status: '201', acl: 'public-read')
end

有关key_starts_with的更多详情,请参阅AWS SDK for Ruby

供参考,这是我的表格,其中添加了key-start数据值:

<%= simple_form_for @asset, html: {class: 'directUpload new_asset', data: { 'form-data' => (@s3_direct_post.fields), 'key-start' => "#{current_project.name}/#{SecureRandom.hex(4)}_" , 'url' => @s3_direct_post.url, 'host' => URI.parse(@s3_direct_post.url).host  } } , :url => project_assets_path(current_project) do |f| %>
    <%= f.input :name %>
    <%= f.input :file, as: :file %>
    <%= f.button :submit, "Add File", class: "addFileButton" %>
<% end %> 

在我的情况下,我只是将它用于单个文件上传,并且只想确保从文件名中删除空格(我是此上传表单的两个用户之一,因此特殊字符或其他文件名问题不是&# 39;关心)。

答案 1 :(得分:0)

在add:callback中,将“key”的s3签名从“/ somefolder / $ {filename}”更改为“/ somefolder / your-new-name”

s3_signatures = { 
                  key: '/somefolder/${filename}',
                  …
                }

$('.fileupload').fileupload({
  url: url,
  type: 'POST',
  formData: s3_signatures, // adding signature for S3
  add: function(e, data){
    s3_signatures['key'] = '/somefolder/your-new-name';
    data.formData = s3_signatures;
    data.submit();
  } …
相关问题