Eric Mitjans Eric Mitjans - 6 months ago 100
Javascript Question

Keeping original format on file rename using AngularJS and ng File Upload

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';

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?


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 +'/'),'/', '.'));

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