[英]Upload file to node server with angular-file-upload
我很抱歉我的英语。 我正在使用 MEAN 堆栈来编写我的应用程序。 我找到了一些上传图片的模块,angular-file-upload 是我的选择。 但是当我上传图像时,控制台上显示的百分比已完成。 我正在检查上传目录。 文件已上传但无法在 Image Viever 中读取。
这是我关于 angular 的代码:
$scope.onFileSelect = function($files) {
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
$scope.upload = $upload.upload({
url: '/posts/upload/',
method: 'POST',
file: file,
}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
}
};
这是我在 Node JS 上的代码:
exports.upload = function(req, res) {
var data = new Buffer('');
req.on('data', function(chunk) {
data = Buffer.concat([data, chunk]);
});
req.on('end', function() {
req.rawBody = data;
fs.writeFile(config.root + path.sep + 'public/upload' + path.sep + uuid.v1(), data ,function(err){
if(err) throw err;
console.log('ok saved')
});
res.send('ok');
});
}
我想我在 Node 上做错了什么,但我找不到它。 请告诉我我的错误。
您需要将上传图像的预览 url 发送回 angular。
在服务器端
req.on('end', function() {
req.rawBody = data;
var imgUrl = '/upload' + path.sep + uuid.v1();
fs.writeFile(config.root + path.sep + 'public' + imgUrl, data ,function(err){
if(err) throw err;
//send back the preview url
res.jsonp({
imgUrl: imgUrl
})
});
客户端
$scope.onFileSelect = function($files) {
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
$scope.upload = $upload.upload({
url: '/posts/upload/',
method: 'POST',
file: file,
}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
$scope.imgurl = data.imgUrl;
});
}
};
您可以像这样显示图像
<img ng-src="{{imgurl}}" ng-show="imgurl" alt="preview for uploaded image" >
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.