Sometimes, we want to create a file object without our JavaScript code.
In this article, we’ll look at how to create a file object with JavaScript.
Create a File Object with the File Constructor
We can create a file with the File
constructor with JavaScript.
For instance, we can write:
const parts = [
new Blob(['you construct a file...'], {
type: 'text/plain'
}),
' Same way as you do with blob',
new Uint16Array([33])
];
const file = new File(parts, 'sample.txt', {
lastModified: new Date(2020, 1, 1),
type: "text/plain"
});
const fr = new FileReader();
fr.onload = (evt) => {
document.body.innerHTML = `
<a href="${URL.createObjectURL(file)}" download="${file.name}">download</a>
<p>file type: ${file.type}</p>
<p>file last modified: ${new Date(file.lastModified)}</p>
`
}
fr.readAsText(file);
We create the parts
array with the parts of a file.
The first entry of parts
is a Blob
instance with the file content.
The first argument of Blob
is the file content in an array.
The 2nd argument of Blob
has the file metadata.
The 2nd and 3rd entries of parts
has more file content.
Next, we use the File
constructor to create a file object.
The first argument is the file content, which we stored in parts
.
The 2nd argument is the file name.
The 3rd argument is some metadata.
Next, we create a FileReader
instance so we can read the file contents.
We set the onload
property of it to watch when the file loads into memory.
In the callback, we get the file metadata from the file
.
And we use URL.createObjectURL
with file
to create a URL so we can download the file from a link we create by setting it as the value of href
.
When we call readAsText
with file
, the onload
method will run.
Now when we click on download, we see the sample.txt file download with the content that we put into parts
in the text file.
Conclusion
We can create a file with the File
constructor. And then we can read the file with the FileReader
object.