如何在 JavaScript 中创建文件对象的修改副本?

How to create a modified copy of a File object in JavaScript?

<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() 的第一个参数必须是数组,而不仅仅是原始文件。

您可以使用 FormData.prototype.append(),它还将 Blob 转换为 File 对象。

let file = event.target.files[0];
let data = new FormData();
data.append("file", file, file.name);
let _file = data.get("file");

更跨浏览器的解决方案

works for me too in modern browsers, but unfortunately it does not work in IE11, since IE11 does not support the File constructor。 但是,IE11 确实支持 Blob 构造函数,因此它可以用作替代方案。

例如:

var newFile  = new Blob([originalFile], {type: originalFile.type});
newFile.name = 'copy-of-'+originalFile.name;
newFile.lastModifiedDate = originalFile.lastModifiedDate;

来源:MSDN - How to create a file instannce using HTML 5 file API?