Greg
Greg

Reputation: 311

How to change property value on file upload?

I am uploading files to server and in front-end, I want to change the names of the files. For that, I wrote this code

     for (var i = 0; i < self.files().length; i++) {
         var file = self.files()[i]; //example value 'test'
         var randomNumber= randomNumber(); //generates some number
         file.name = randomNumber+ '-' + file.name; //should be '7-test' but still is 'test'
         formData.append('Pdf' + i, file);
     }

Did I miss something?

EDIT : before this code is called, this is written

self.files = ko.observableArray();
self.selectFile = function (data, e) {
    self.files.removeAll();

    for (var i = 0; i < e.target.files.length; i++) {
         self.files.push(e.target.files[i]);
    }
};

I'm trying to rename files in front-end because couldn't do it in back-end. It's type is HttpPostedFileBase and I can not rename it

Upvotes: 0

Views: 71

Answers (1)

MKougiouris
MKougiouris

Reputation: 2861

Why dont you just change the original script like so, and forget about the first snippet completely:

self.selectFile = function (data, e) {
    self.files.removeAll();        

    for (var i = 0; i < e.target.files.length; i++) {
        let curFile = e.target.files[i];
        curFile.name = ''+randomNumber()+'-'+curFile.name;
        self.files.push(curFile);
    }
};

Upvotes: 1

Related Questions