使用 $http 发送带角度的 multipart/form-data 文件 [英] Send multipart/form-data files with angular using $http
问题描述
我知道对此有很多问题,但我无法让它发挥作用:
I know there are a lot of questions about this, but I can't get this to work:
我想将文件从输入上传到 multipart/form-data 中的服务器
I want to upload a file from input to a server in multipart/form-data
我尝试了两种方法.第一:
I've tried two approaches. First:
headers: {
'Content-Type': undefined
},
导致例如对于图像
Content-Type:image/png
虽然它应该是 multipart/form-data
while it should be multipart/form-data
另一个:
headers: {
'Content-Type': multipart/form-data
},
但这需要一个边界标题,我认为不应该手动插入...
But this asks for a boundry header, which I believe should not be manually inserted...
有什么干净的方法可以解决这个问题?我读过你可以做
What is a clean way to solve this problem? I've read that you can do
$httpProvider.defaults.headers.post['Content-Type'] = 'multipart/form-data; charset=utf-8';
但我不希望我的所有帖子都是多部分/表单数据.默认应该是 JSON
But I don't want all my posts to be multipart/form-data. The default should be JSON
推荐答案
看一下 FormData 对象:https://developer.mozilla.org/en/docs/Web/API/FormData
Take a look at the FormData object: https://developer.mozilla.org/en/docs/Web/API/FormData
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
这篇关于使用 $http 发送带角度的 multipart/form-data 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!