如何在HTTP POST(angularjs + expressjs)中将数据与文件一起发送? [英] How to send data along with file in http POST (angularjs + expressjs)?
问题描述
我实现了文件上传.前端代码来自流行的教程.我在服务中发送POST:
I implemented file uploading. Front-end code is taken from popular tutorial. I send POST in service:
myApp.service('fileUpload', ['$http', function ($http) {
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(){
});
}
}]);
后端典型的multer用法:
Typical multer usage in back-end:
exports.postFile = function (req, res) {
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, '../documents/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
upload(req, res, function (err) {
if (err) {
res.json({error_code: 1, err_desc: err});
return;
}
res.json({error_code: 0, err_desc: null});
})
};
那行得通.
如何在同一POST中发送一些数据,比如说字符串"additional info"
?
How to send some data in the same POST, let say string "additional info"
?
我试图在服务中添加数据,即:
I tried to add data in service, i.e.:
...
var fd = new FormData();
fd.append('file', file);
fd.append('model', 'additional info');
$http.post(uploadUrl, fd, {...})
它似乎已发送,但我不知道如何在后端接收它.试图在req
中找到它(没有成功).
It seems to be sent, but I don't know how to receive it in back-end. Tried to find it in req
(without success).
推荐答案
要在一个POST请求中发送数据(即json)和文件,请将两者都添加到表单数据中:
To send data (i.e. json) and file in one POST request add both to form data:
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
var info = {
"text":"additional info"
};
fd.append('data', angular.toJson(info));
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
在服务器端,它位于req.body.data
中,因此可以像这样接收它:
On server side it's in req.body.data
, so it can be received i.e. like this:
upload(req, res, function (err) {
if (err) {
res.json({error_code: 1, err_desc: err});
return;
}
console.log(req.body.data);
res.json({error_code: 0, err_desc: null});
})
这篇关于如何在HTTP POST(angularjs + expressjs)中将数据与文件一起发送?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!