【发布时间】:2014-06-29 05:41:36
【问题描述】:
你如何在nodejs端解析formdata?
我正在向 nodejs 服务器发送 http POST 请求。 这是Javascript的sn-p(其中有角度)。我的目标是上传文件并向其中添加 JSON。所以我要上传一张图片和一个包含 {account: xx , sitename:xyz, etc..}
的 json$scope.upload[index] = $upload.upload({
url : 'http://localhost:1215/facility',
method: $scope.httpMethod,
headers: {'Content-Type': 'multipart/form-data','X-Requested-With':'XMLHttpRequest'},
data : $scope.selectedSite,
withCredentials:true,
file: $scope.selectedFiles[index],
fileFormDataName: 'myFile'
}).then(function(response) {
$scope.uploadResult.push(response.data);
}, null, function(evt) {
$scope.progress[index] = parseInt(100.0 * evt.loaded / evt.total);
}).xhr(function(xhr){
xhr.upload.addEventListener('abort', function(){console.log('aborted complete')}, false);
});
}
我正在使用允许我构建表单数据的 angular-upload-file。它将 selectedSite json 与文件和文件名结合在一起。在 github 上找到它,它正在解决问题。 [角度文件上传][1]https://github.com/danialfarid/angular-file-upload。 Fiddler 证实了这一点。
这个库 angular-file-upload 的工作方式是带有 XMLHTTPREQUEST 的 http 将导致正文引用看起来像这样的表单数据
{
site:xyz,
account:xxx,
etc
Myfile: somefile.txt: fileContent
}
在服务器端,无论我做什么,我都无法获取 json 键的值(例如 xyz)或文件的内容。我还没有尝试保存文件或操作 json。
router.post('/', passport_utils.ensureAuthenticated,
function(req, res)
{
var data ,file= {};//reconstruct site from formdata
console.log("req.body" + req.body);
//jsonData = JSON.stringify(data);
for(var field in req.body){
console.log(field); //prints all the json elements but not the file or the filename
if(field.match(‘site’))
console.log("HI username "+ field.site) ;
if(field.match('account'))
console.log("hi data " + field.name);
res.send(200);
}
我尝试使用 field[jsonkey] 或 field.jsonkey 来获取值。上面的 for 循环确认我有键但没有值。所有这些都会导致该值“未定义”。 显示键值但不显示值
【问题讨论】:
-
if(field.match(‘site’))不是有效的 JavaScript。
标签: javascript json node.js angularjs