8

I am using Nodejs + Multer +angularjs for uploading files on 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 perfectly and the file is successfully uploaded.

but this redirect me to "/multer" after uploading the file (because of the form element).
How do i stay on the same page??..possibly using angularjs
so i tried this:

making a HTML angular file:

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

and a 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 SOMEONE HELP ME WITH THE CODE FOR MAKING A POST REQUEST WITH A FILE OBJECT FOR UPLOADING USING MULTER FROM ANGULARJS CONTROLLER ?

thanks

4
  • Did you find any solution? Commented Dec 10, 2015 at 13:53
  • 1
    @SimranKaur yes i found a solution:) Commented Dec 10, 2015 at 15:23
  • 1
    @SimranKaur I have posted the answer Commented Dec 10, 2015 at 15:37
  • hi @GauravGupta I stuck in same kind of problem. Please assist me to save my time. Commented Feb 21, 2019 at 9:28

1 Answer 1

24

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!

Sign up to request clarification or add additional context in comments.

6 Comments

for this, "fd.append('file', file)" and, this "upload.single('file')" – big thanks!
Gives me {Error: Not Found: POST /multer in the terminal and POST XHR https://..../multer [HTTP/1.1 404 Not Found 220ms] in the explorer debugger how can I fix this?
Can you tell me where this Nodejs server route file code will be adding because I am new in angularjs and I am not able to understand this part .
@nolags try keeping the changes in app.js at the beginning, just after you define app. Mostly you have it after your error handler.
Thanks for the solution. Successfully integrated in a project generated based on Angular-Fullstack-Generator with Yeoman Adding it in the controller of the related API
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.