Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript not able to rename file before upload

I am trying to upload file to aws s3. before i upload i want to rename it by adding timestamp to file name. but i am geting an error as 'Cannot assign to read only property 'name' of object '#''

here is the code

let file = e.target.files[0];
let timeStamp = (new Date()).getTime();
let fileExt = file.name.split('.')[file.name.split('.').length-1];
let fileNameWithoutExt = file.name.replace(`.${fileExt}`,'');
let newFileName = fileNameWithoutExt + '_' + timeStamp + '.' + fileExt;
file.name = newFileName;

enter image description here

like image 837
TerribleDeveloper Avatar asked Jan 29 '18 06:01

TerribleDeveloper


3 Answers

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);
}
like image 83
Kaiido Avatar answered Sep 21 '22 19:09

Kaiido


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);
like image 26
ajay hariyal Avatar answered Sep 19 '22 19:09

ajay hariyal


  • 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"

like image 43
Alex Nikulin Avatar answered Sep 22 '22 19:09

Alex Nikulin