JavaScript not able to rename file before upload
Yep that sounds like a weird rule to set it as Read-only, but it's what it is...So the workaround, not so hard, is to create a new File object from your previous one...
var previous_file = new File(['foo'], 'file.txt', {type: 'text/plain'});try{ previous_file.name = 'hello.txt';}catch(e){}console.log(previous_file.name); // didn't work// so we just create a new File from it...var new_file = new File([previous_file], 'hello.txt');console.log(new_file);
But also note that if you need to support older browsers that don't support the File constructor, then you can override this file name in a FormData that you will send to your sever:
var file = new File(['foo'], 'text.txt', {type:'text/plain'});var formdata = new FormData();// this will override the file nameformdata.append('file', file, 'hello.txt');// and now you can send this formdata through xhr// for demo, we will just log its contentfor(let entry of formdata.entries()) { console.log(entry);}
The append() method of FormData accepts a third optional filename parameter.
// new file name as a variable with timestampconst newName = new Date().getTime() + event.target.files[0].name; fd.append('file[]', event.target.files[0], newName);
- You can't change a name of an already created file.
- You can createnew instance of file with new file name, like in a post above.ButFile constroctor is not supported by all browsers (is not supported at IE and EDGE supporting table).
- You can put newfile name to key property of your amazon uploadhttps://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html
instead of key = "folder1/folder2/${filename}"
you can write key = "folder1/folder2/youfilename.txt"