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

可紊 提交于 2019-11-27 02:41:28

问题


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

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';
}

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

So how does one clone a File object?


回答1:


My solution lay in the File constructor:

https://developer.mozilla.org/en-US/docs/Web/API/File#Implementation_notes

Which itself is an extension of 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 });
}

Note the first argument to File() must be an array, not simply the original file.




回答2:


You can use FormData.prototype.append(), which also converts a Blob to a File object.

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



回答3:


A more cross browser solution

The accepted answer works for me too in modern browsers, but unfortunately it does not work in IE11, since IE11 does not support the File constructor. However, IE11 does support the Blob constructor so it can be used as an alternative.

For example:

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

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



来源:https://stackoverflow.com/questions/41008024/how-to-create-a-modified-copy-of-a-file-object-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!