Я пытаюсь создать страницу angularJS, в которой указаны имя пользователя, пароль и профиль профиля. Я использую настраиваемую директиву fileUpload, а затем отправляю как поля, так и файлы в виде запроса на множественную форму.Как получить объект json и файлы в многопартийной форме?
На стороне сервера я могу получить файлы в порядке, используя многопартийность, но данные полей отображаются как {[object object]}, и я не могу добраться до него. Пробовал 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>
угловой код контроллера:
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!");
});
};
});
BACKEND Node.js апи -
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, чтобы я мог создать запись в mongo, получить запись _id и использовать ее для обозначения моих файлов. Обратите внимание, что я могу получить как файлы, так и поля в порядке. Мне просто нужна помощь в преобразовании входящих полей в JSON.
Действительно оцените любую помощь, которую вы можете предоставить.
Обязательно ознакомьтесь - https://nodejs.org/api/util.html#util_util_inspect_object_options поможет вашему отладки ... – Gary