nodejs + multer + angularjs for uploading without redirecting

后端 未结 1 1471
粉色の甜心
粉色の甜心 2020-12-03 18:48

I am using Nodejs + Multer +angularjs for uploading files on the server.

i have a simple HTML file:

相关标签:
1条回答
  • 2020-12-03 19:06

    Angularjs directive:

    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 file:

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

    Angularjs Controller:

    $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 server route file:

    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'));
    

    Enjoy!

    0 讨论(0)
提交回复
热议问题