Eric Mitjans
Eric Mitjans

Reputation: 2179

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

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?

Upvotes: 0

Views: 866

Answers (2)

developer033
developer033

Reputation: 24894

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!

Upvotes: 1

Mike Cluck
Mike Cluck

Reputation: 32511

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))
   }
   ...

Upvotes: 2

Related Questions