【问题标题】:How to upload files to AWS-S3 with Angular $http PUT如何使用 Angular $http PUT 将文件上传到 AWS-S3
【发布时间】:2017-01-05 02:18:57
【问题描述】:

在我的 Angular 应用程序中,我尝试使用 $http.put(url, file) 将文件上传到 AWS-S3。

但是它不起作用,我返回一个 HTTP-403 Forbidden,告诉我计算的签名 s3 与我提供的签名不同,但是如果我使用 curl 发出相同的请求,例如 curl -X PUT -T file url,那么一切正常,文件被上传.所以要么 $http.put 的工作方式不好(对于这个任务),要么 curl 有一些魔力。谁能详细说明一下?

【问题讨论】:

  • 我现在查了一下,但没有一个答案适用于我的情况。使用 curl 我可以使它工作,但不能使用 $http :/

标签: javascript angularjs amazon-web-services amazon-s3 angularjs-http


【解决方案1】:

使用$http服务上传文件时,设置Content-Type: undefined很重要。

  var config = { headers: {
                   "Content-Type": undefined,
                  }
               };

  var promise = $http.put(url, file, config);

$http 服务的默认内容类型是application/json。通过设置Content-Type: undefined,$http 服务将省略Content-Type 标头,XHR API 将Content-Type 标头设置为文件的标头。

【讨论】:

    【解决方案2】:

    仅供参考:

    我不知道为什么$http 不起作用..即使我根据这个主题发现了奇怪的事情。

    所以首先我像这样从 html 中“获取”文件:

    <input flex="40" type="file" onchange="angular.element(this).scope().$parent.selectAttachment(this)">
    

    因为我不想为此测试目的创建指令。 selectAttachment 函数只是将文件设置为我的控制器的属性。

    然后看起来没问题,我可以阅读例如 this.attachment.name 或 this.attachment.size,但是当我写 $http.put(url, this.attachment) 时,我得到了签名不匹配错误。

    然后我尝试了与本教程中相同的 XHR:https://devcenter.heroku.com/articles/s3-upload-node

    永远不会走运...

    然后,作为最后的手段,我尝试通过不通过 Angular 设置文件来获取文件,而是通过 const file = document.getElementById('report-attachment').files[0]; 最后它对我有用。有趣的是,使用 getElementById 和使用 $http 获取文件仍然无法正常工作,我尝试过的 1 或 2 个 3rd 方角度上传器都没有,仅使用 XHR o.o

    对我有用的最终“解决方案”:

    HTML:

    <input flex="40" id="report-attachment" type="file">
    

    JS:

                const file = document.getElementById('report-attachment').files[0];
                const url = r && r.data;
                const xhr = new XMLHttpRequest();
                xhr.open('PUT', url);
                xhr.onreadystatechange = () => {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {
                            console.debug('success');
                        } else {
                            console.error('error');
                        }
                    }
                };
                xhr.send(file);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-23
      • 2018-07-07
      • 1970-01-01
      • 1970-01-01
      • 2019-12-06
      • 2021-05-14
      • 2020-04-29
      • 1970-01-01
      相关资源
      最近更新 更多