我实现了文件上传。前端代码取自流行的tutorial。我在服务中发送POST:
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用法:
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"
?
我试图在服务中添加数据,即:
...
var fd = new FormData();
fd.append('file', file);
fd.append('model', 'additional info');
$http.post(uploadUrl, fd, {...})
似乎已发送,但我不知道如何在后端接收它。试图在req
找到它(没有成功)。
答案 0 :(得分:3)
要在一个POST请求中发送数据(即json)和文件,请将两者添加到表单数据中:
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
,因此可以接收,例如:
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});
})
答案 1 :(得分:0)
您可以从req.files获取该文件,并使用fs.writeFile保存。
fs.readFile(req.files.formInput.path, function (err, data) {
fs.writeFile(newPath, data, function (err) {
if (err) {
throw err;
}
console.log("File Uploaded");
});
});
答案 2 :(得分:-1)
您可以这样做:
$http({
url: url,
method: 'POST',
data: json_data,
headers: {'Content-Type': 'application/json'}
}).then(function(response) {
var res = response.data;
console.log(res);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
或者只是将data属性添加到您的函数中。
var userObject = {
email: $scope.user.email,
password: $scope.user.password,
fullName: $scope.user.fullName
};
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
data: userObject,
headers: {'Content-Type': 'application/json'}
})
您可以在后端尝试这样的事情。
req.on('data', function (chunk) {
console.log(chunk);
});