I need to change a file's name before uploading it but the property is readonly:
https://developer.mozilla.org/en-US/docs/Web/API/File
so
this.imageFile.name = newFileName;
doesnt work.
I looked at other questions here but the answers are all - 'create a new file using the File contructor'.
eg
var file = new File(['foo'], 'newName', {type:'img/jpg'});
But the constructor is not available in IE or edge.
In the end I found form data has good support on caniuse.com and you can provide a new file name like so:
var newFileName = file.filename + "new";
var formData = new FormData();
formData.append('file', file, newFileName);
In between these two solutions, I tried another:
Object.defineProperty(this.imageFile, 'name', {
writable: true
});
this.imageFile.name = newFileName;
Clearly this one is a hack, but it worked. I decided not to go with this as FormData append method takes a filename to solve this problem, I just dont understand why it is a readonly property if I can manually change the descriptor and it works fine.
from Is it ok to change a JavaScript file name by changing it's writable property descriptor?
No comments:
Post a Comment