0

I'm using the ng-file-upload to upload images in a web app.

Upload process works good, but when I try to give each file a unique name using momentJS, it won't automatically keep the format and save it without file extension.

For example, image.jpg will become 12-07-2016-23-36-44.

I managed to fix this using the following code, but then it will save all images to JPG even if they are not (PNG, GIF...)

$scope.uniquelogo = moment().format('DD-MM-YYYY-HH-mm-ss') + '.jpg';

Upload.upload({
   url: 'upload.php',
   data: {
    file: file,
    name: Upload.rename(file, $scope.uniquelogo)
   }

How could I use Upload.rename() and still keep the original file format?

2
  • Can you get the extension from the original filename and use that instead of .jpg? Commented Jul 12, 2016 at 22:00
  • @MikeC I don't see anything about it in the documentation.. Commented Jul 12, 2016 at 22:01

2 Answers 2

2

You can retrieve the extension from the original file name and use that instead of .jpg.

function getFileExtension(filename) {
  return filename
    .split('.')    // Split the string on every period
    .slice(-1)[0]; // Get the last item from the split
}

$scope.uniquelogo = moment().format('DD-MM-YYYY-HH-mm-ss');

Upload.upload({
   url: 'upload.php',
   data: {
    file: file,
    name: Upload.rename(file, $scope.uniquelogo + getFileExtension(file.name))
   }
   ...
Sign up to request clarification or add additional context in comments.

Comments

1

You can access the property type to get the extension, but it comes for example:

  1. image/(jpeg|png)
  2. video/mp4

So you can use the string methods String.prototype.substring() + String.prototype.lastIndexOf() to get only the part that you want:

name: Upload.rename(file, $scope.uniquelogo + file.name.substring(file.type.lastIndexOf('/'), file.name.length).replace('/', '.'));

Note: I used the replace method to replace the "/" for ".", but you can also do it by hand (just putting $scope.uniquelogo + '.' + file.name.substring(file.type.lastIndexOf('/') + 1, file.name.length)

I hope it helps!

Comments

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.