nodejs + multer + angularjs,无需重定向即可上传

时间:2015-10-05 20:05:43

标签: angularjs node.js multer

我使用Nodejs + Multer + angularjs在服务器上上传文件。

我有一个简单的HTML文件:

<form action="/multer" method="post" enctype="multipart/form-data">
<input type="file" id="photo" name="photo"/> 
<button id="Button1">Upload</button>
</form>

Nodejs部分:

var multer  = require('multer');

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads/')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
})

app.post('/multer', upload.single('photo'), function (req, res) {
    res.end("File uploaded.");
});

这完美无缺并且文件已成功上传。

但是在上传文件后(由于表单元素),我将其重定向到“/ multer” 我如何留在同一页? ..可能使用angularjs
所以我试过这个:

制作HTML角度文件:

<section data-ng-controller="myCtrl">
<input type="file" id="photo" name="photo"/> 
<button id="Button1" ng-click="f()">Upload</button>
</section>

和Angularjs控制器:

angular.module('users').controller('myCtrl',[$scope,function($scope){
    $scope.f=function(){
        var photo = document.getElementById('photo');
        var file = photo.files[0];
        if (file) {

            //code to make a post request with a file object for uploading?????

            //something like..
            //$http.post('/multer', file).success(function(response) {
            //console.log("success");
            //});
        }
    }
}]);


是否有人可以使用该代码帮助我使用文件对象进行后期请求,以便使用来自ANGULARJS控制器的MULTER上传?

感谢

1 个答案:

答案 0 :(得分:22)

Angularjs指令:

angular.module('users').directive('fileModel', ['$parse', function ($parse) {
return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        var model = $parse(attrs.fileModel);
        var modelSetter = model.assign;

        element.bind('change', function(){
            scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
            });
        });
    }
};
}]);

Angular html文件:

<input type="file" file-model="myFile"/><br><br>
<button ng-click="uploadFile()">Upload</button>

Angularjs控制器:

$scope.uploadFile = function(){

        var file = $scope.myFile;
        var uploadUrl = "/multer";
        var fd = new FormData();
        fd.append('file', file);

        $http.post(uploadUrl,fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(){
          console.log("success!!");
        })
        .error(function(){
          console.log("error!!");
        });
    };

Nodejs服务器路由文件:

var multer  = require('multer');
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads/')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname+ '-' + Date.now()+'.jpg')
    }
});
var upload = multer({ storage: storage });

app.post('/multer', upload.single('file'));

享受!