简体   繁体   English

使用预先签名的POST URL将文件上载到AWS S3时设置随机文件名

[英]Set random file name when upload file to AWS S3 with pre-signed POST url

I use signed POST url with jQuery-file-upload to upload image to AWS S3 directly. 我将签名的POST网址与jQuery-file-upload结合使用,以将图像直接上传到AWS S3。

It work fine on my PC, but when I test with iPhone, I fine out that iOS will upload any picture with same name like image.png or image.jpeg . 它在我的电脑上工作正常,但是当我用iPhone测试时,我很清楚iOS会上传任何名称相同的图片,如image.pngimage.jpeg

That make the image upload finished last replace any image upload successed before it. 这使得图像上传完成最后替换之前成功的任何图像上传。

I generate presigned post with boto3 in Python3 like this: 我在Python3中使用boto3生成了预先签名的帖子,如下所示:

post = s3.generate_presigned_post(
    Bucket='?????????',
    Key=get_random_string(8,'simple') + '/${filename}',
    Fields={
        'success_action_status': '201',
        'acl': 'public-read'
    },
    Conditions=[{
            'success_action_status': '201'
        },
        {
            'acl': 'public-read'
        },
        ["starts-with", "$Content-Type", ""]
    ]
)
post['fields'] = json.dumps(post['fields'])

And here is my javascript code: 这是我的javascript代码:

$(function () {
    'use strict';

    var form = $('#fileupload');
    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload({
        dropZone: $('#dropzone'),
        previewMaxHeight: 300,
        previewMaxWidth: 300,
        acceptFileTypes:  /(\.|\/)(gif|jpe?g|png)$/i,
        dataType: 'XML',
        getFilesFromResponse: function (data) {
            var key = $(data.jqXHR.responseXML).find("Key").text();
            var url = $(data.jqXHR.responseXML).find("Location").text();
            return [{
                url: url,
                name: key,
                thumbnailUrl: url,
            }];
        },
    }).on('fileuploadsubmit', function (e, data) {
        data.formData = (function (form) {
            var r = form.serializeArray();
            $.each(form.data('theform-data'), function(k, v) {
                r.push({name: k , value: v})
            });
            return r;
        })(data.form);
        data.formData.push({name: "Content-Type" , value: data.files[0].type});
    });
});

The get_random_string(8,'simple') in Python just can prevent same file name in different upload, but it cannot prevent same file name when user upload multifile at the same time (because they upload with same pre-signed POST url). Python中的get_random_string(8,'simple')只能在不同的上传中阻止相同的文件名,但是当用户同时上传多文件时(因为它们使用相同的预签名POST URL进行上传),它不能阻止相同的文件名。

So I wonder if there has any way that I can set random file name when upload file to AWS S3 with pre-signed POST url? 因此,我想知道在使用预签名的POST URL将文件上传到AWS S3时,是否可以设置随机文件名?

I found out that this would work: 我发现这可行:

$(function () {
    'use strict';

    var form = $('#fileupload');
    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload({
        dropZone: $('#dropzone'),
        previewMaxHeight: 300,
        previewMaxWidth: 300,
        acceptFileTypes:  /(\.|\/)(gif|jpe?g|png)$/i,
        dataType: 'XML',
        getFilesFromResponse: function (data) {
            var key = $(data.jqXHR.responseXML).find("Key").text();
            var url = $(data.jqXHR.responseXML).find("Location").text();
            return [{
                url: url,
                name: key,
                thumbnailUrl: url,
            }];
        },
    }).on('fileuploadsubmit', function (e, data) {
        data.formData = (function (form) {
            var r = form.serializeArray();
            $.each(form.data('theform-data'), function(k, v) {
                if (k == "key") {
                    var filename = v.split("/");
                    var random_prefix = filename[0];
                    var ext = data.files[0].name.split(".").slice(-1)[0];
                    v = random_prefix + '/'
                        + (function (length, chars) {
                            var result = '';
                            for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
                            return result;
                        })(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
                        + '.' + ext.toLowerCase();
                };
                r.push({name: k , value: v})
            });
            return r;
        })(data.form);
        data.formData.push({name: "Content-Type" , value: data.files[0].type});
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将文件上传到AWS中的预签名URL? - How do I upload a file to a pre-signed URL in AWS? 如何使用 angular 或 javascript 中的预签名 url 将文件上传到 S3 存储桶 - how to upload file to S3 bucket using pre-signed url in angular or javascript 使用angular + aws-sdk-js +预签名网址将文件上传到S3 - Uploading a file to S3 with angular + aws-sdk-js + pre-signed url S3使用预先签名的URL从浏览器上传图片 - S3 Upload image with pre-signed url from browser 如何使用预签名的 URL 而不是凭证直接从浏览器上传到 AWS S3? - How to upload to AWS S3 directly from browser using a pre-signed URL instead of credentials? 通过预签名URL将PUT上传到S3时拒绝签名 - Signature Denied in PUT upload to S3 with Pre-Signed URL 通过 multipart/form-data 内容类型上传文件时,在 Safari 中,预签名后上传到 S3 间歇性失败 - Pre-signed Post Uploads to S3 fails intermittently in Safari when uploading file via multipart/form-data content type Dropzone 客户端通过文件上传到 AWS 预签名 url 调整大小 - Dropzone client side resize with file upload to AWS pre-signed url 从没有弹出窗口阻止程序的预签名 URL 下载 S3 文件 - Download S3 file from pre-signed URL without popup blocker 如何通过 Node.js 中的预签名 URL 将文件上传到 AWS S3 存储桶 - How to Upload File to AWS S3 Bucket via pre signed URL in Node.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM