JavaScript not able to rename file before upload
The append() method of FormData accepts a third optional filename parameter.
// new file name as a variable with timestamp
const 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 create new instance of file with new file name, like in a post above.But File constroctor is not supported by all browsers (is not supported at IE and EDGE supporting table).
- You can put new file name to key property of your amazon upload https://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"
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 name
formdata.append('file', file, 'hello.txt');
// and now you can send this formdata through xhr
// for demo, we will just log its content
for(let entry of formdata.entries()) {
console.log(entry);
}