【问题标题】:S3 signed url not working with ajaxS3签名的网址不适用于ajax
【发布时间】:2018-06-24 19:25:10
【问题描述】:

我正在尝试使用预签名 URL 将文件直接上传到 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。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

这是不工作的代码:

$.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);
    });

请帮忙

【问题讨论】:

  • 您是否尝试在您的 ajax 配置对象中将 crossDomain 作为 true 传递?它应该在那之后工作。

标签: jquery angularjs ajax amazon-s3


【解决方案1】:

请查看: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>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
    <ExposeHeader>ETag</ExposeHeader>
  </CORSRule>
</CORSConfiguration>

【讨论】:

猜你喜欢
  • 2018-02-26
  • 1970-01-01
  • 2017-12-22
  • 2021-03-17
  • 1970-01-01
  • 1970-01-01
  • 2017-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多