Search code examples
angularjsnode.jsmulterng-file-upload

HOw to save file with original file name with ng file upload on the server


I am trying to upload my files with ng file upload but they are uploaded with some different file name on the server.I want them to get saved with the file name they have originally with their correct extension(.jpg,.pdf). Below is my code. Controller:

$scope.uploadPic = function (file) {
         $scope.advert.userDetails={
        "name":userDetails.name,
        "email":userDetails.email,
        "role":userDetails.role
    }
        file.upload = Upload.upload({
            url: '/api/uploaders/uploads',
            method: 'POST',
            fields: {
                details: $scope.advert
            },
            file: file,
            fileFormDataName: 'photo'
        });

    file.upload.then(function (response) {
        console.log("Postcontroller: upload then ");
        $timeout(function () {
            file.result = response.data;
        });
    }, function (response) {
        if (response.status > 0)
            $scope.errorMsg = response.status + ': ' + response.data;
    });

    file.upload.progress(function (evt) {
        // Math.min is to fix IE which reports 200% sometimes
        file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
        console.log("PostController: upload progress " + file.progress);
    });
            file.upload.success(function (data, status, headers, config) {
        // file is uploaded successfully
        console.log('file ' + config.file.name + 'is uploaded successfully. Response: ' + data);
        console.log(data);
    });

}

Api:

var multer = require('multer');
var upload = multer({ dest: 'server/uploads/images'});

Solution

  • It's not ng-upload changing the filename, it's multer. This is for security reasons.
    In a nutshell, you wouldn't want someone to know the exact path of a file they've uploaded - what if it were malicious? They could potentially execute it.

    If you really want, however, you can do this on your API side:

    var multer = require('multer');
    
    var storage = multer.diskStorage(
        {
            destination: 'server/uploads/images',
            filename: function (req, file, cb) {
                cb(null, file.originalname);
            }
        }
    );
    
    var upload = multer(storage);