How to generate AWS S3 pre-signed URL request without knowing Content-Type?

我怕爱的太早我们不能终老 提交于 2019-12-08 18:49:21

问题


I am generating in server side a pre-signed URL request with the following parameters for GeneratePresignedUrlRequest : bucket, key, expiration = in 1 hour and method = PUT.

In my Angular app, I am uploading the file using ng-file-upload

Upload.http({
    url: $scope.signedUrl,
    method: "PUT",
    headers : {
        'Content-Type': $scope.file.type
    },
    data: $scope.file
});

The problem is that I always have a 403 response unless I set the type of the file in GeneratePresignedUrlRequest.contentType.

The problem is that I can't predict in advance what type of file the user will choose (image/png, image/jpeg, text/plain...).

How can I generate a pre-signed url that accept all kinds of content-type ? I tried setting it to null, it keeps sending 403 errors.

Thanks.


回答1:


I just ran into this problem, and just got it working. Replace your Upload.http code with the following:

var reader = new FileReader();
var xhr = new XMLHttpRequest();

xhr.open("PUT", $scope.signedUrl);
reader.onload = function(evt) {
  xhr.send(evt.target.result);
};
reader.readAsArrayBuffer($scope.file);

The problem ends up being that S3 is looking for a specific Content-Type (binary/octet-stream), which it infers when you omit the Content-Type header.




回答2:


The value from the Content-Type header is a mandatory component of the signature. It isn't possible to pre-sign a PUT URL without knowing the value that will be sent.

A POST upload is more flexible, since you can allow any Content-Type in the signed policy.




回答3:


One possible solution might be if you keep track of the extension? eg: ends with ".jpg" -> content type = "image/jpeg", end with ".zip" -> content type = "application/octet-stream".

Ref: get the filename of a fileupload in a document through javascript



来源:https://stackoverflow.com/questions/32443197/how-to-generate-aws-s3-pre-signed-url-request-without-knowing-content-type

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