使用angular-file-upload将文件上载到节点服务器

时间:2014-02-20 11:26:23

标签: node.js angularjs file-upload express

对不起我的英语。我使用MEAN堆栈来写我的应用程序。我发现一些上传图像的模块和angular-file-upload是我的选择。但是当我上传图片时,控制台上显示的百分比已经完成。我检查上传目录。文件已上传但无法在Image Viever中读取。

这里是我的角度代码:

        $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做错了但我找不到它。请告诉我我的错误。

1 个答案:

答案 0 :(得分:0)

您需要将上传图片的预览网址发送回角度。

在服务器端

 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" >