[英]node.js to upload image using multer shows undefined
在這里,我正在嘗試從2個不同的文件輸入上傳文件,我可以將其上傳到前端,但在后端它仍未undefined
。 嘗試了幾件事但沒有奏效。
HTML:
<input type="file" name="file1" file-model = "file1"/>
<input type="file" name="file2" file-model = "file2"/>
<button ng-click = "uploadFile()">UPLOAD FILES</button>
指示:
angular.module('myApp').directive('fileModel', ['$parse',
function($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function() {
scope.$apply(function() {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}
])
服務:
angular.module('myApp').service('fileUpload', ['$http',
function($http) {
this.uploadFileToUrl = function(file, uploadUrl) {
var fd = new FormData();
fd.append('file1', file);
fd.append('file2', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
})
}
}
]);
控制器:
angular.module('myApp')
.controller('ContactCtrl', ['$scope', 'fileUpload', '$http',
function($scope, fileUpload, $http) {
$scope.uploadFile = function() {
var file1 = $scope.file1;
var file2 = $scope.file2;
console.log('file is ');
console.dir(file1);
console.dir(file2);
var uploadUrl = '/upload';
fileUpload.uploadFileToUrl({
file1, file2
}, uploadUrl);
};
服務器:
function upload(req,res){
console.log(req.files.file1);
}
在nodejs的服務器端無法找到一個文件的情況,即你可以在/api/v1/uploadfile": [{ method: "POST", action: controllers.advertController.videoUpload, middleware: [multipartMiddleware], views: { json: views.jsonView } }],
提供multerobject /api/v1/uploadfile": [{ method: "POST", action: controllers.advertController.videoUpload, middleware: [multipartMiddleware], views: { json: views.jsonView } }],
global.multipartMiddleware = multipart();
在服務器端代碼在請求的中間件使用multipartMiddleware。
控制器(在此將正確的參數傳遞給服務)
var file ={} file.file1=file1; file.file2=file2; fileUpload.uploadFileToUrl(file, uploadUrl);
服務(如果你想一次上傳多個文件使用循環)
angular.module('myApp').service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file1', file.file1);
fd.append('file2', file.file2);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
}
}]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.