我在本地运行MeanJS,我安装了 angular-file-upload 并按照here的教程配置了我的 client.controller 。
$scope.onFileSelect = function(image) {
if (angular.isArray(image)) {
image = image[0];
console.log(image);
}
// This is how I handle file types in client side
if (image.type !== 'image/png' && image.type !== 'image/jpeg') {
alert('Only PNG and JPEG are accepted.');
return;
}
$scope.uploadInProgress = true;
$scope.uploadProgress = 0;
$scope.upload = $upload.upload({
url: '/usedcars/image',
headers: {'Content-Type': 'multipart/form-data'},
method: 'POST',
file: image
}).progress(function(event,data) {
console.log('progress'+data);
$scope.uploadProgress = Math.floor(event.loaded / event.total);
if(!$scope.$$phase) {
$scope.$apply();
}
}).success(function(data, status, headers, config) {
console.log('success');
$scope.uploadInProgress = false;
// If you need uploaded file immediately
$scope.uploadedImage = JSON.parse(data);
}).error(function(err) {
$scope.uploadInProgress = false;
console.log('Error uploading file: ');
});
};
并创建了一个服务器路由:
app.route('/usedcars/image')
.post(usedcars.postImage);
这是我的 server.controller :
var uuid = require('node-uuid'),
multiparty = require('multiparty'),
fs = require('fs');
exports.postImage = function(req, res) {
console.log(res);
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
var file = files.file[0];
var contentType = file.headers['content-type'];
var tmpPath = file.path;
var extIndex = tmpPath.lastIndexOf('.');
var extension = (extIndex < 0) ? '' : tmpPath.substr(extIndex);
// uuid is for generating unique filenames.
var fileName = uuid.v4() + extension;
var destPath = 'modules/usedcars/upload' + fileName;
// Server side file type checker.
if (contentType !== 'image/png' && contentType !== 'image/jpeg') {
fs.unlink(tmpPath);
return res.status(400).send('Unsupported file type.');
}
fs.rename(tmpPath, destPath, function(err) {
if (err) {
return res.status(400).send('Image is not saved:');
}
return res.jsonp(destPath);
});
});
};
最后我的 view.html :
Upload image
<input type="file" data-ng-file-select="onFileSelect($files)"
accept="image/png, image/jpeg">
<span data-ng-if="uploadInProgress">
Upload progress: {{ uploadProgress }}
</span>
<img data-ng-src="uploadedImage" data-ng-if="uploadedImage">
但是我收到了这个错误:
POST http://localhost:3000/usedcars/image 400 (Bad Request)
我正在使用chrome进行开发,我尝试了不同的插件,如 ng-flow ,但错误仍然相同。我是AngularJS的新手前端开发人员,对node.js没有任何先验知识。是什么导致出现此错误?