我正在尝试使用ng-file-upload
和multer
进行文件上传。 我的代码当前看起来像这样。
HTML文件
<form class="form-inline" ng-submit="startUpload()">
<div class="form-group">
<fieldset>
<label for="city" class="hidden"></label>
<input id="city" class="form-control" type="text" name="city"
ng-model="city" placeholder="City" />
<label for="description" class="hidden"></label>
<input id="description" class="form-control" type="text" name="description"
ng-model="description" placeholder="Description" />
<label for="images" class="hidden"></label>
<input id="images" class="form-control" type="file" name="images"
placeholder="Images" accept="image/*"
ngf-select="uploadFiles($files, $invalidFiles)" />
<input class="btn btn-custom btn-submit" type="submit" value="Upload">
</fieldset>
</div>
角度控制器
angular.module('upload').controller('uploadController', function($scope, Upload) {
var uploadUrl = 'http://localhost:1337/api/v1/upload';
var images;
$scope.uploadFiles = function(files, errFiles) {
images = files;
};
$scope.startUpload = function() {
var data = {
location: $scope.city,
title: 'test title',
description: $scope.description,
};
Upload.upload({
url: uploadUrl,
headers : {
'Content-Type': 'multipart/form-data'
},
arrayKey: '',
data: data,
files: images
});
};
});
后端API
var multer = require('multer');
var upload = multer({ dest : 'source/public/assets/img/test/' });
app.post(versionUrl + '/create-entry', upload.array('images'), function(req, res, next) {
console.log(req.body) // this contains all text data
console.log(req.files) // this is always an empty array
});
由于这是我第一次这样做,所以我很沮丧,它不起作用。 互联网上有很多示例,提供了完全相同的代码-仍然不适合我。
我很高兴所有建议,可以帮助我解决这个问题。
您需要设置images: images
data
对象中的images: images
:
var data = {
location: $scope.city,
title: 'test title',
description: $scope.description,
images: images
};
Upload.upload({
url: uploadUrl,
arrayKey: '',
data: data,
});