【问题标题】:object file being sent instead of file information while trying to upload file through http尝试通过http上传文件时发送目标文件而不是文件信息
【发布时间】:2017-06-09 23:07:33
【问题描述】:

尝试通过 Angular $http 上传文件。我正在设置 Content-Type 并按照大多数地方的建议用 FormData 对象包装它。但是,浏览器在 http 请求的请求负载中发送 [object data]。

服务调用:

let fd = new FormData();

            fd.append('file', file);
            return $q((resolve, reject) => {
                $http.post(url, fd, {
                    headers: {
                        'Content-Type': undefined,
                        'X-Token': undefined
                    }
                }).then(
                        success => resolve(success.data),
                        error => reject(error)
                    );
            });

关于为什么浏览器不能编码这个文件的想法?请注意,到目前为止,我已经尝试过 docx、zip、mp4 文件格式。它们都产生相同的结果。

请求负载:

------WebKitFormBoundaryqfOlKmKqvArA9pz6
Content-Disposition: form-data; name="file"

[object File]
------WebKitFormBoundaryqfOlKmKqvArA9pz6--

使用的标记:

<input type="file" id="file-tutorial-{{$index}}-{{language.iso2}}" name="file-tutorial-{{$index}}-{{language.iso2}}"
                                     onchange="angular.element(this).scope().ctrl.addFile(this);">

Ctrl.addFile:

addFile(element) {
    service.uploadFile(element.files[0]);
    this.$scope.$digest();
}

element.files[0] 或文件对象:

{lastModified:1496720186000
 lastModifiedDate:Mon Jun 05 2017 23:36:26 GMT-0400 (EDT)
 name:"Adil Sulaiman Resume.docx"
 size:25456
 type:"application/vnd.openxmlformats-
 officedocument.wordprocessingml.document"
 webkitRelativePath:""}

【问题讨论】:

    标签: javascript angularjs http


    【解决方案1】:

    您似乎缺少 angular.identity,这会阻止 Angular 对您发送的文件执行任何操作,例如序列化它。看解释here

    您正在使用本机 onchange 事件,该事件超出了角度范围。看看这个article 了解如何访问文件对象。

    可以在here找到工作演示

    【讨论】:

    • 也试过了,但没有骰子。
    • 你在使用带有 input[type=file] 的 ng-model 吗?
    • 我添加了一个演示,展示了一个工作示例,实际发布将无法正常工作,但您会看到请求中不存在 [Object object]
    猜你喜欢
    • 2016-04-11
    • 2019-09-22
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    相关资源
    最近更新 更多