nodejs + multer + angularjs上传而不redirect

我正在使用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."); }); 

这工作完美 ,文件成功上传。

但是在上传文件后(因为表单元素),我redirect到“/ multer”。
我如何留在同一页面? ..可能使用angularjs
所以我试过这个:

制作一个HTMLangular度文件:

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

有人可以帮我用这个代码做一个上传文件的请求,使用angular度控制器的MULTER上传一个文件对象吗?

谢谢

       

网上收集的解决方案 "nodejs + multer + angularjs上传而不redirect"

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

请享用!