A File object inherits from Blob and is extended with filesystem-related capabilities.
There are two ways to obtain it.
First, thereâs a constructor, similar to Blob:
new File(fileParts, fileName, [options])
filePartsâ is an array of Blob/BufferSource/String values.fileNameâ file name string.optionsâ optional object:lastModifiedâ the timestamp (integer date) of last modification.
Second, more often we get a file from <input type="file"> or dragânâdrop or other browser interfaces. In that case, the file gets this information from OS.
As File inherits from Blob, File objects have the same properties, plus:
nameâ the file name,lastModifiedâ the timestamp of last modification.
Thatâs how we can get a File object from <input type="file">:
<input type="file" onchange="showFile(this)">
<script>
function showFile(input) {
let file = input.files[0];
alert(`File name: ${file.name}`); // e.g my.png
alert(`Last modified: ${file.lastModified}`); // e.g 1552830408824
}
</script>
The input may select multiple files, so input.files is an array-like object with them. Here we have only one file, so we just take input.files[0].
FileReader
FileReader is an object with the sole purpose of reading data from Blob (and hence File too) objects.
It delivers the data using events, as reading from disk may take time.
The constructor:
let reader = new FileReader(); // no arguments
The main methods:
readAsArrayBuffer(blob)â read the data in binary formatArrayBuffer.readAsText(blob, [encoding])â read the data as a text string with the given encoding (utf-8by default).readAsDataURL(blob)â read the binary data and encode it as base64 data url.abort()â cancel the operation.
The choice of read* method depends on which format we prefer, how weâre going to use the data.
readAsArrayBufferâ for binary files, to do low-level binary operations. For high-level operations, like slicing,Fileinherits fromBlob, so we can call them directly, without reading.readAsTextâ for text files, when weâd like to get a string.readAsDataURLâ when weâd like to use this data insrcforimgor another tag. Thereâs an alternative to reading a file for that, as discussed in chapter Blob:URL.createObjectURL(file).
As the reading proceeds, there are events:
loadstartâ loading started.progressâ occurs during reading.loadâ no errors, reading complete.abortâabort()called.errorâ error has occurred.loadendâ reading finished with either success or failure.
When the reading is finished, we can access the result as:
reader.resultis the result (if successful)reader.erroris the error (if failed).
The most widely used events are for sure load and error.
Hereâs an example of reading a file:
<input type="file" onchange="readFile(this)">
<script>
function readFile(input) {
let file = input.files[0];
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function() {
console.log(reader.result);
};
reader.onerror = function() {
console.log(reader.error);
};
}
</script>
FileReader for blobsAs mentioned in the chapter Blob, FileReader can read not just files, but any blobs.
We can use it to convert a blob to another format:
readAsArrayBuffer(blob)â toArrayBuffer,readAsText(blob, [encoding])â to string (an alternative toTextDecoder),readAsDataURL(blob)â to base64 data url.
FileReaderSync is available inside Web WorkersFor Web Workers, there also exists a synchronous variant of FileReader, called FileReaderSync.
Its reading methods read* do not generate events, but rather return a result, as regular functions do.
Thatâs only inside a Web Worker though, because delays in synchronous calls, that are possible while reading from files, in Web Workers are less important. They do not affect the page.
Summary
File objects inherit from Blob.
In addition to Blob methods and properties, File objects also have name and lastModified properties, plus the internal ability to read from filesystem. We usually get File objects from user input, like <input> or DragânâDrop events (ondragend).
FileReader objects can read from a file or a blob, in one of three formats:
- String (
readAsText). ArrayBuffer(readAsArrayBuffer).- Data url, base-64 encoded (
readAsDataURL).
In many cases though, we donât have to read the file contents. Just as we did with blobs, we can create a short url with URL.createObjectURL(file) and assign it to <a> or <img>. This way the file can be downloaded or shown up as an image, as a part of canvas etc.
And if weâre going to send a File over a network, thatâs also easy: network API like XMLHttpRequest or fetch natively accepts File objects.
ÙØ¸Ø±Ø§Øª
<code>Ø§Ø³ØªÙØ§Ø¯Ù Ú©ÙÛØ¯Ø Ø¨Ø±Ø§Û ÚÙØ¯Û٠خط â کد را درÙ٠تگ<pre>ÙØ±Ø§Ø± دÙÛØ¯Ø Ø¨Ø±Ø§Û Ø¨ÛØ´ از د٠خط کد â Ø§Ø² ÛÚ© جعبÙÙ Ø´ÙÛ Ø§Ø³ØªÙØ§Ø¯Ù Ú©ÙÛØ¯. (plnkrØ jsbinØ codepenâ¦)