我一直在关注FormData tutorial here,但是尚未了解formData object的工作原理。
我的输入表格
<input type="file" id="file-id" class="w300px rounded4px" name="file" placeholder="PDF file">
<button class="btn-upload-pdf" ng-click="asub.uploadPDF()">Upload</button>
这是上传按钮功能:
this.uploadPDF = () => {
const formData = new FormData();
const fileInput = document.getElementById('file-id');
const file = fileInput.files[0];
formData.append('pdf-file', file);
console.log('formData', formData)
return ApiFactory.insightPDF(formData).then((res) => {
console.log('res', res);
return res;
});
};
当我注销
fileInput
对象.files[0]
时,我看到我刚刚附加的文件:这似乎意味着该对象应该足以发送到POST。但是,这是下一步:
formData.append('pdf-file', file);
我先注销
formData
,然后再将其发送到Factory中,这就是结果,我看不到关键的pdf-file
或PDF,只是一堆方法?文件也附加在哪里? formData如何包含实际的PDF?我需要从我假定的formData对象中附加一些东西:
发出POST请求的工厂
const insightPDF = (formData) => {
console.log(' formData', formData)
return $http.post('/app/api/insights_pdf', formData).then((res) => {
console.log('PDF uploaded res', res)
return res;
}).catch(apiError);
};
最佳答案
设置Content-Type: undefined
张贴由FormData API创建的对象时,将内容类型 header 设置为undefined
很重要。
const insightPDF = (formData) => {
console.log(' formData', formData)
var config = { headers: {'Content-Type': undefined} };
return $http.post('/app/api/insights_pdf', formData, config)
.then((res) => {
console.log('PDF uploaded res', res)
return res;
}).catch(apiError);
};
通常,AngularJS框架会自动将内容类型 header 添加为
application/json
,以覆盖XHR Send() method设置的内容类型。当XHR API发送FormData object时,它将自动将内容类型设置为具有适当边界的multipart/form-data
。从文档中:
像FormData objects一样的blobs是非JavaScript的主机定义对象。并不是所有的属性都可以通过
console.log
或console.dir
看到。 Files是Blob的一种特殊类型。数据不一定是从磁盘加载的。通常,仅在特定API需要时才从磁盘流式传输数据。避免额外的开销-直接发送文件
multipart/form-data
中的内容使用base64 encoding,这会增加33%的额外开销。如果仅上传一个文件,则直接发送文件Blob效率更高。//MORE Efficient; Avoids base64 encoding overhead
const insightPDF = (dataObject) => {
var config = { headers: {'Content-Type': undefined} };
return $http.post('/app/api/insights_pdf', dataObject, config)
.then((res) => {
console.log('PDF uploaded res', res)
return res;
}).catch(apiError);
};
var file = inputElem[0].files[0];
insightPDF(file);
如果服务器可以直接接受二进制内容,则最好以这种方式发送文件。 XHR API将自动将内容类型设置为文件的内容类型。