j查询-文件-上传前重命名文件

jQuery-File-Upload rename file before upload

本文关键字:重命名 文件 查询 -文件      更新时间:2023-09-26

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

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

谢谢

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

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 也知道这一点。 本教程建议控制器set_s3_direct_post方法中的key值为:

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

key 方法要求文件名与创建帖子 URL 时提供的内容匹配(它不会,因为我没有使用动态${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的更多详细信息,请参阅适用于 Ruby 的 AWS 开发工具包。

作为参考,这是我的表单,其中包含添加的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 %> 

就我而言,我只将其用于单个文件上传,只想确保从文件名中删除空格(我是此上传表单的两个用户之一,因此文件名的特殊字符或其他问题不是问题)。

在添加:回调中,将"密钥"的 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();
  } …