Renaming a File() object in JavaScript

浪尽此生 提交于 2019-12-01 02:40:51

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

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});

try this:

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

note: this is for a image type, you have to change this type with type you're actually using.

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 that should form the new blob. By saying:

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

you are not saying "copy to the end of the file" (which is what I think is your aim), you are saying "copy the whole blob except the last byte".

As @carestad says

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

followed by creating a new File() object should create an exact copy with a new name.

Note that with a png, the file will be considered invalid without the final byte.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!