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

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

问题描述

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

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