Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 362
2540625 Avatar asked Dec 07 '16 01:12

2540625


People also ask

How do you make a copy of a file in JavaScript?

The Copy() method is used to copy a file. overwrite is a Boolean value indicating whether to overwrite an existing file of the same name. 32.9.

How do you copy properties from one object to another in JavaScript?

Object.assign() The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.

How many ways we can clone object in JavaScript?

JavaScript provides 3 good ways to clone objects: using spread operator, rest operator and Object. assign() function. Aside from just cloning objects, using object spread and Object. assign() lets you add or updated properties when creating the clone.


2 Answers

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.

like image 145
2540625 Avatar answered Oct 04 '22 01:10

2540625


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"); 
like image 41
guest271314 Avatar answered Oct 04 '22 00:10

guest271314