S3签名网址无法使用ajax

时间:2018-01-16 06:31:37

标签: jquery angularjs ajax amazon-s3

我正在尝试使用预先签名的网址将文件直接上传到S3,但无法使其正常运行,检查了所有相关帖子,但无法找到任何解决方案。我能够在另一个项目中通过angular上传,下面的代码正在运行。

const req = new HttpRequest('PUT', preSignedUrl, file, {
    reportProgress: true
});

$this._http.request(req).subscribe(e => {
    if (e.type === HttpEventType.UploadProgress) {
        ...
    } else if (e instanceof HttpResponse) {
        ...
    }
})

然而,现在我试图用Ajax获得相同的输出,但我得到403 Forbidden。对预检请求的响应没有通过访问控制检查:否'访问控制 - 允许 - 来源'标头出现在请求的资源上。

以下代码不起作用:

$.ajax({
    type: 'PUT',
    url: preSignedUrl,
    // Content type must much with the parameter you signed your URL with
    headers: {
        "Content-Type": file.type,
        'x-amz-acl': 'public-read'
    },
    // this flag is important, if not set, it will try to send data as a form
    processData: false,
    // the actual file is sent raw
    data: file
})
    .success(function () {
        alert('File uploaded');
    })
    .error(function () {
        alert('File NOT uploaded');
        console.log(arguments);
    });

请帮助

1 个答案:

答案 0 :(得分:0)

请检查:Upload a file with $.ajax to AWS S3 with a pre-signed url

 $.ajax({
      type: 'PUT',
      url: "<YOUR_PRE_SIGNED_UPLOAD_URL_HERE>",
      // Content type must much with the parameter you signed your URL with
      contentType: 'binary/octet-stream',
      // this flag is important, if not set, it will try to send data as a form
      processData: false,
      // the actual file is sent raw
      data: theFormFile
    })
    .success(function() {
      alert('File uploaded');
    })
    .error(function() {
      alert('File NOT uploaded');
      console.log( arguments);
    });

在浏览器中配置CORS:link

<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedHeader>*</AllowedHeader>
    <ExposeHeader>ETag</ExposeHeader>
  </CORSRule>
</CORSConfiguration>