如何以多方forms接收json对象和文件?

我试图build立一个张贴用户名,密码和个人资料图片的angularJS页面。 我正在使用一个自定义fileUpload指令,然后发送这两个字段和文件作为多部分forms的请求。

在服务器端,我可以使用多方获取文件,但字段数据显示为{[对象对象]},我无法得到它。 试过JSON.stringify,但也不起作用。

这是我的代码:

视图

<form ng-submit="submitForm(user)"> <input type="text" ng-model="user.username" placeholder="user name"> <input type="text" ng-model="user.age" placeholder="age"> <input type="password" ng-model="user.password" placeholder="password"> <input type="file" file-upload multiple/> <input type="submit" class="btn btn-danger">Send</button> </form> 

angular度控制器代码:

 var app = angular.module('testphoto', []); app.directive('fileUpload', function () { return { scope: true, link: function (scope, el, attrs) { el.bind('change', function (event) { var files = event.target.files; for (var i = 0;i<files.length;i++) { scope.$emit("fileSelected", { file: files[i] }); } }); } }; }); app.controller('photoController', function($scope, $http){ $scope.files = []; //listen for the file selected event $scope.$on("fileSelected", function (event, args) { $scope.$apply(function () { //add the file object to the scope's files collection $scope.files.push(args.file); console.log('$scope.files has', $scope.files) }); }); $scope.submitForm = function(user) { $http({ method: 'POST', url: 'http://localhost:3050/user', headers: { 'Content-Type': undefined }, transformRequest: function(data) { var fd = new FormData(); fd.append('user', user); for (var i = 0; i < data.files.length; i++) { fd.append('file' + i, data.files[i]); } return fd; }, data: { model: $scope.model, files: $scope.files } }). success(function (data, status, headers, config) { }). error(function (data, status, headers, config) { alert("failed!"); }); }; }); 

后端node.js api –

 app.post('/user', function (req, res) { var count=0 var form = new multiparty.Form(); var uploadDir = __dirname + '/../uploads/fullsize/' var size = ''; var fileName = ''; var data = {} var fields = [] var fieldCount = 0 form.on('field', function(name, val){ fields.push('{"'+name+'":'+val+'}') console.log('fields array now has:', fields[fieldCount]) var fieldsStringified = JSON.stringify(fields[fieldCount]) console.log('fieldsStringified:',fieldsStringified) fieldCount++ }); form.on('file', function(name,file){ count++ var tmp_path = file.path var target_path = uploadDir + 'profilePic' + count+'.jpg'; mv(tmp_path, target_path, function(err){ if (err) { console.error(err.stack) } console.log('file '+target_path+ 'saved' ) }) }) //--- end app.post() 

我理想希望看到的事情是以JSON的forms接收用户对象,这样我就可以在mongo中创buildlogging,获取logging_id并使用它来命名我的文件。 请注意,我可以同时接收文件和字段。 我只需要帮助将传入的字段转换为JSON。

非常感谢您提供的帮助。

问题解决了。 得到的数据作为“字段”,然后转换成json对象使用json.parse()

 //Push field onto an array form.on('field', function(name, val){ fields.push('"' +name+ '"'+ ':'+'"'+val+'"') }); //finally convert array to json obj form.on('close', function(){ var str = '{'+fields.toString() +'}' var user = JSON.parse(str) 
Interesting Posts