如何在JavaScript中创建File对象的修改后的副本? [英] How to create a modified copy of a File object in JavaScript?

查看:103
本文介绍了如何在JavaScript中创建File对象的修改后的副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<输入类型= file> 接收的文件的属性是只读的。

Properties of files received from an <input type="file"> are read-only.

例如,以下尝试重新写入 file.name 的尝试将失败,或者无声地抛出 TypeError:无法分配为只读对象'#< File>'的属性'name'。

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创建副本{},文件)失败(创建一个空对象)。

Attempting to create a copy via Object.assign({}, file) fails (creates an empty object).

那么如何克隆 File 对象?

推荐答案

我的解决方案位于 File 构造函数中:

My solution lay in the File constructor:

https:// developer.mozilla.org/zh-CN/docs/Web/API/File#Implementation_notes

这本身就是的扩展Blob

https://developer.mozilla.org/zh-CN/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中创建File对象的修改后的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆