从 <input type="file">
接收的文件的属性是只读的.
Properties of files received from an <input type="file">
are read-only.
例如,以下重写 file.name
的尝试要么静默失败,要么抛出 TypeError: Cannot assign to read only property 'name' of object '#<File>'代码>.
For example, the following attempt to re-write file.name
would either fail silently or throw 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)
创建副本失败(创建一个空对象).
Attempting to create a copy via Object.assign({}, file)
fails (creates an empty object).
那么如何克隆一个 File
对象呢?
So how does one clone a File
object?
我的解决方案在于 File
构造函数:
My solution lay in the File
constructor:
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()
的第一个参数必须是一个数组,而不仅仅是原始文件.
Note the first argument to File()
must be an array, not simply the original file.
这篇关于如何在 JavaScript 中创建文件对象的修改副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!