带文件对象的角度发布json [英] Angular post json with file object
问题描述
我正在尝试使用具有以下结构的简单对象进行发布呼叫:
I'm trying to make a post call with a simple object that has this structure:
{"name": "file.txt", "file": file}
file
是我从输入文件中获得的对象.
file
is an object I get from an input file.
我已尝试拨打此电话,但我无法提交对象:
I have tried to make this call but i can't submit my object:
var elements = $element[0];
var file = elements.getElementsByTagName('input')[0].files[0];
this.fileName = file.name;
var formData = new FormData();
formData.append('file', file);
var url = 'http://localhost:8080/upload';
var config = {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
};
$http.post(url, formData, config)
.success(function(data){
$log.info(data);
})
.error(function(err){
$log.error(err);
});
关于为什么这种方法不起作用的任何想法?
Any ideas on why this isn't working?
推荐答案
我最近不得不做些笑话,花了很多时间才能使请求通过,但是这种配置最终对我们有用.
I recently had to do something smilar, it took a lot of fenagling to get the request to go through, but this configuration finally worked for us.
sendObj.append("file", fileObj.file, fileObj.file.name);
$http({
headers: {'Content-Type': undefined},
processData:false,
method: 'POST',
cache: false,
url: sendUrl,
data: sendObj,
transformRequest: function(data, headersGetterFunction) {
return data; // do nothing! FormData is very good!
}
})
另一方面,在服务器端还花费了很多时间,所以根据您所拥有的,您可能需要执行其他操作.这是给我们的Spring服务器的.
On a side note, it also took a lot of messing about on the server side so depending on what you have, you may need to do something else. This was for our Spring server.
这篇关于带文件对象的角度发布json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!