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?
现在file.name
是只读属性,我发现这是在浏览器中重命名 File 对象的最佳方法:
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.
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.
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
You can use
FileSystemEntry.moveTo(newParent[, newName][, successCallback][, errorCallback]);
to rename a file or directory.
It's from MDN : https://developer.mozilla.org/en-US/docs/Web/API/FileSystemEntry/moveTo
Assuming f is original file object, just use spread operator, example of regexing the name:
let newF = {
...f,
name: f.name.toString().replace(/[^0-9A-Za-z.\-_()]/gi, '')
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.