S3 PUT doesn't work with pre-signed URL in javascript

这一生的挚爱 提交于 2019-12-04 05:40:55

Adding

headers: {'Content-Type': 'text/plain;charset=UTF-8'},

To AJAX

function ajaxUsingPresignedUrlPut() {
            $.ajax({
                url: presignedURLPUT,
                type: 'PUT',
                data: 'blah blah blah',
                headers: {'Content-Type': 'text/plain;charset=UTF-8'},
                success: function () {
                    console.log('Uploaded data successfully.');
                }
            }).done(function (data) {
                console.log("DONE : " + data);
            }).fail(function (arg1, arg2) {
                console.log("FAIL");        
            });
        }

And setting content type while generating the URL fixed the issue

    GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, KEY);        
    request.setContentType("text/plain;charset=UTF-8");
    //...

there is actually a better way to set the content-type which seemed to have been the problem here:

$.ajax({
    url : s3presignedUrl,
    type : "PUT",
    data : file,
    dataType : "text",
    cache : false,
    contentType : file.type,
    processData : false
})

The important part for you is contentType : file.type where file.type comes from the <input type=file> onchange event (which actually reveals this.files which can then be iterated over...)

you can grab the complete client files from my php+js solution here: https://github.com/JoernBerkefeld/s3SignedUpload

In case you do not want to restrict content-type like Nickolay Kondratyev suggests, you can set Content-Type like this:

headers: {'Content-Type': ' '},

Note, there is a string with a space char. Not null, not undefined, empty string or any other falsy value. And it works.


Update: this does not work anymore, S3 now detects mime type and adds it anyway

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!