我正在尝试使用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
});
由于这是我第一次做这样的事情,我完全感到沮丧,因为它不起作用。互联网上有很多例子,提供完全相同的代码 - 但这个代码对我来说仍然无效。
我会对所有建议感到高兴,帮助我解决这个问题。
答案 0 :(得分:3)
您需要在images: images
对象中设置data
:
var data = {
location: $scope.city,
title: 'test title',
description: $scope.description,
images: images
};
Upload.upload({
url: uploadUrl,
arrayKey: '',
data: data,
});