Nodejs + multer + angularjs to download without redirection

I am using Nodejs + Multer + angularjs to upload files to the server.

I have a simple HTML file:

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

Nodejs Part:

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

this works great and the file uploaded successfully.

but this redirects me to "/ multer" after loading the file (due to the form element).
How can I stay on one page? .. possibly using angularjs
so i tried this:

creating angular HTML file:

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

and Angularjs controller:

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


Can anyone help me with the receipt of the request code after a file of files for downloading the use of the MULTER OF ANGULARJS CONTROLLER?

thanks

+6
source share
1 answer

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 it!

+21
source

All Articles