Renaming a File () Object in JavaScript

I would like my users to be able to rename the file before downloading it.

I have a File object in Javascript that has a name property that is already set, but I would like it to be updated. Right now, when the obvious myFile.name = "new-name.txt" returns an error, this property is read-only.

What is the best way to change the name property to a JavaScript File object?

+9
source share
4 answers

You can add an input tag with a name on it and hide the name property from the user. On the server, just use input as the name and ignore the default name.

+2
source

Now that file.name is a file.name -only property, I have found that this is the best way to rename a File object in a browser:

 const myNewFile = new File([myFile], 'new_name.png', {type: myFile.type}); 
+10
source

try it:

 var blob = file.slice(0, file.size, 'image/png'); var newFile = new File([blob], 'name.png', {type: 'image/png'}); 

note: this is for an image type, you must change this type with the type that you are actually using.

+4
source

In response to Alexander Taborda’s answer ... The first and second parameters of Blob.slice () are the start and end bytes of the original blob, which should form a new blob. Saying:

 var blob = file.slice(0,-1); 

you do not say “copy to end of file” (this is what I consider your goal), you say “copy the entire block except the last byte”.

As @carestad says

 var blob = file.slice(0, file.size); 

and then creating a new File () object should create an exact copy with the new name.

Please note that with png a file is considered invalid without a trailing byte.

From: https://developer.mozilla.org/en-US/docs/Web/API/Blob/slice

+2
source

All Articles