meanstacky
meanstacky

Reputation: 397

ng-file-upload How to use Upload.rename(file, newName)

I am using ng-file-upload and multer to store files in an uploads folder and I also save the filename to database but of course not at the same instant. So if I want to save the original filename, multer will do this like:

filename: function (req, file, cb) {
cb(null, file.originalname);

I can use

cb(null, file.originalname + '-' + Date.now());

to make the name unique but then the filename in the database (taken from the ng-file-upload service) is different. I want to use Upload.rename(file, newName) as on the github/danialfarid/ng-file-upload page but all my attempts to use it have failed. This is the ng-file-upload code (first part)

$scope.uploadPic = function(files) {
        for(var i = 0; i < $scope.files.length; i++) {
          var $file = $scope.files[i];
          (function(index) {
            $scope.upload[index] = Upload.upload({
              url: '/',
              method: 'POST',
              file: $file,
            }).progress(function (evt) {
              $scope.files[index].progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
            }).then(function (response) {
              $timeout(function () {
                $file.result = response.data;

I have tried var newName = $file.name + '-' + Date.now()

but then I am unsure of how to apply Upload.rename(file, newName)

I thought if I set the new name before multer gets hold of it then the uploads folder and the database will have the same name. At least that's the idea. Can anyone help?

Upvotes: 0

Views: 2173

Answers (2)

laide
laide

Reputation: 41

in the upload options, set the file key as the name of the file and use the same key for the multer options e.g:

if you have this for your ng-file-upload options:

$scope.upload[index] = Upload.upload({
          url: '/',
          method: 'POST',
          nameOfImage: $file,
        })

for multer, you should also have

upload.single('nameOfImage')

I tried this using multer v1.2.0 and ng-file-upload 12.2.12

Upvotes: 3

meanstacky
meanstacky

Reputation: 397

I was using an older version of ng-file-upload (7.X.X) which didn't have this in ng-file-upload.js

this.rename = function (file, name) {
    file.ngfName = name;
    return file;
  };

I updated to version 10.0.2 So now I can use Upload.rename($file, 'preview1.jpg'); and the file is saved with the new name.

Upvotes: 0

Related Questions