一尘不染

nodejs + multer + angularjs用于上传而无需重定向

angularjs

我正在使用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>

Node.js部分:

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”(由于form元素)。
我如何留在同一页面上?..可能使用angularjs,
所以我尝试了这个:

制作一个HTML angular文件:

<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进行文件上传吗?

谢谢


阅读 309

收藏
2020-07-04

共1个答案

一尘不染

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]);
            });
        });
    }
};
}]);

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

请享用!

2020-07-04