【问题标题】:How to create a modified copy of a File object in JavaScript?如何在 JavaScript 中创建文件对象的修改副本?
【发布时间】:2016-12-07 01:40:44
【问题描述】:

<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 对象呢?

【问题讨论】:

    标签: javascript file copy clone


    【解决方案1】:

    更跨浏览器的解决方案

    The accepted answer 在现代浏览器中也适用于我,但不幸的是它不适用于 IE11,因为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?

    【讨论】:

      【解决方案2】:

      您可以使用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");
      

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-15
          • 2010-09-16
          相关资源
          最近更新 更多