上传文件到节点服务器角文件上传
我对我的英语很抱歉。我用MEAN堆栈书面方式我的应用程序。我发现上传图像和角文件上传是我的选择一些模块。但是,当我上传的图片在控制台上的百分比显示完成。我检查上传目录。该文件上传,但可以在图像Viever看不懂。
I'm sorry about my English. I am use MEAN stack for writting my app. I find out some modules for uploading image and angular-file-upload is my choice. But when I upload the image the percent show on console completed. I'm check upload directory. The file is uploaded but can not read in Image Viever.
下面的角度我code:
Here my code on 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);
});
}
};
在节点JS在这里,我的code:
Here my code on 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');
});
}
我想我做错事与节点,但我不能找到它。请告诉我我的错误。
I guess I do something wrong with Node but I can't find out it. Please tell me what my mistake.
您需要为上传的图片发送preVIEW URL回到棱角分明。
You need to send the preview url for the uploaded image back to 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" >