从 <input type="file">
接收到的文件的属性是只读的。
例如下面尝试重写file.name
要么默默地失败,要么抛出 TypeError: Cannot assign to read only property 'name' of object '#<File>'
.
<input onchange="onchange" type="file">
onchange = (event) => {
const file = event.target.files[0];
file.name = 'foo';
}
尝试通过 Object.assign({}, file)
创建副本失败(创建一个空对象)。
那么如何克隆一个File
目的?
最佳答案
我的解决方案在于 File
构造函数:
https://developer.mozilla.org/en-US/docs/Web/API/File#Implementation_notes
它本身是 Blob
的扩展:
https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob
let file = event.target.files[0];
if (this.props.distro) {
const name = 'new-name-here' + // Concat with file extension.
file.name.substring(file.name.lastIndexOf('.'));
// Instantiate copy of file, giving it new name.
file = new File([file], name, { type: file.type });
}
请注意 File()
的第一个参数必须是一个数组,而不仅仅是原始文件。
关于javascript - 如何在 JavaScript 中创建文件对象的修改副本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41008024/