简体   繁体   中英

Cannot replace the file name using Angular.js ng-file-upload

I am trying to rename the file name after uploading the file using Angular.js ng-file-upload . But what is happening in my case when I am removing ngf-min-height="400" ngf-resize="{width: 400, height:400}" properties. I am providing my code below:

<input type="file"  data-size="lg" name="bannerimage" id="imagefile1"  ng-model="file" ngf-pattern="image/*" accept="image/*"  ngf-max-size="2MB" ngf-min-height="400" ngf-resize="{width: 400, height:400}"   custom-on-change="uploadFile"  ngf-select="onFileSelect($file);" >

My controller side code is given below:

$scope.onFileSelect = function($files) {
         fileURL=$files;
         $scope.imageData='';
    }
var file=fileURL;
var today=(Math.random() * new Date().getTime()).toString(36).replace(/\./g, '');
var newpath=today+"_"+ file.name;
file.name=newpath;

In the above code I am adding a random number to file name and replacing it. In this case it's coming properly, but if I am removing ngf-min-height="400" ngf-resize="{width: 400, height:400}" from file input like below.

<input type="file"  data-size="lg" name="bannerimage" id="imagefile1"  ng-model="file" ngf-pattern="image/*" accept="image/*"  ngf-max-size="2MB"   custom-on-change="uploadFile"  ngf-select="onFileSelect($file);" >

In this case I cannot replace the new file name and I don't need to restrict the file height and width .

The Upload Service of ng-file-upload has a method for this. Here is an example:

$scope.$watch('dropFile', function () {
    uploadFile($scope.dropFile);
});

function uploadFile(file) {
  if (!file) {
    return;
  }

  file = Upload.rename(file, "newName.ext");

  Upload.upload({
        url: <api url for upload>,
        data: {file: file}
    }).then(function (resp) {
      //successful
    }, function (resp) {
        //error
    }, function (evt) {
       //progress
    });
}

try this code

<input type="file"  data-size="lg" name="bannerimage" id="imagefile1"  ng-model="file" accept="image/*" ng-file-select="onFileSelect($files[0]);" >

$scope.onFileSelect =function(file){
    filename = 'jihin.' + file.name.split(".")[1];
    var imgFile = new File([file], filename, {type:file.type});
    console.log(imgFile);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM