Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming a File() object in JavaScript

I'd like for my users to be able to re-name a file before uploading it.

I have a File object in Javascript which has a name property that is already set, but i'd like for this to be able to be updated. Right now doing the obvious myFile.name = "new-name.txt" returns an error that this property is read only.

What's the best way of changing the name property on a JavaScript File object?

like image 814
FiniteLooper Avatar asked Jun 09 '15 13:06

FiniteLooper


People also ask

How do I change a filename in a file object?

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

What is the method of rename () a file?

To rename a file or folder: Right-click on the item and select Rename, or select the file and press F2 . Type the new name and press Enter or click Rename.

How do I rename a file in node JS?

Node FS Rename File – To rename file with Node FS, use fs. rename(new_file_name, old_file_name, callback_function) for asynchronous file rename operation and use fs. renameSync(new_file_name, old_file_name) for synchronous file rename operation.

Can we rename a file in Java?

In Java we can rename a file using renameTo(newName) method that belongs to the File class.


1 Answers

Now that file.name is a read-only property, I've found this to be the best method to rename a File object in the browser:

const myNewFile = new File([myFile], 'new_name.png', {type: myFile.type}); 
like image 186
PaulMest Avatar answered Oct 08 '22 13:10

PaulMest