Hur läser man javascript file js
Read, Edit & Write Files in Client-Side JavaScript
Lately I've been working on a side-project, which was based around reading and manipulating files to generate anpassad thumbnails for Vivaldi browser's speed dials. inom was able to do it all inre the browser, without any server-side processing, and inom want to share with you everything that I've learned.
This guide covers:
- using objectURLs and FileReader to read files from the user's filesystem
- getting a file's resultat like: storlek, type and more
- showing previews of selected image files
- handling errors and loading states
- CHEATSHEET AT THE END
It also acts as an introduction to my guide on using the API, which fryst vatten coming very soon, so stay tuned for that!
To allow your users to select a en samling dokument eller en elektronisk lagring av data from their device, you will first have to create an with the type of file.
To actually get the files from this input, you will need to tillgång the property of the input element.
It's best to do that bygd registering a change event listener on the input element.
For example, suppose you have a file input on your page with id select-fileThis way a callback function will be called every time a user selects a file.
The way you do that will depend on the ramverk you're using. To man this guide as widely applicable as possible, we will be using vanilla JS.
The resulting selectedFile fryst vatten a object.
The en samling dokument eller en elektronisk lagring av data input gives us objects, so in addition to the contents of the en samling dokument eller en elektronisk lagring av data itself, we have tillgång to some additional kunskap, such as:
- - the file's name, including the extension but without the path (e.g.
"")
- - the file's storlek in bytes. To get the storlek in a more human readable format, you can use a library like filesize or bytes. For simple use cases, you can even write your own konvertering logic.
- - the file's MIME type (e.g. "text/plain", "image/png")
- - the gods modified date of the en samling dokument eller en elektronisk lagring av data, represented as the number of milliseconds since the operativsystem epoch (January 1, at midnight).
You can use the Date constructor object.
s also have two other properties: and , the first of which fryst vatten deprecated and the other non-standard, so you should probably avoid using them.
getting a file's information like: size, type and moreKeep in mind that all of these properties are read-only.
Files & Blobs
In addition to
contains a generic file's information, along with resultat about its storlek and type. fryst vatten actually just a more specialised , used to företräda specifically files in a user's filesystem. It inherits all of Blob's methods and properties and contains some additional upplysning about the file's name and gods modified date.
These two are basically interchangeable, and you can use one almost everywhere you can use the other.
If you absolutely need to omvandla them though, you can do so using the other type's constructor.
Okay, so we know how to select and get resultat about files, but how do we actually read what's inre them? Well, that depends on what kind of en samling dokument eller en elektronisk lagring av data it fryst vatten and what you want to do with it.
To read a file in Javascript: Create an HTML file field – file" id="picker"> Get the selected file – let selected = mentById("picker")For the purposes of this article, we will only focus on images and ord files.
The most flexible and well-supported method of reading a file's contents fryst vatten the FileReader API. It's an event driven API, so instead of simply calling a function and getting the file's contents, we must take some extra steps.
Let's början with reading a skrivelse file:
- First we get the en samling dokument eller en elektronisk lagring av data input element, and förteckning a change event listener on it bygd assigning a callback function to its property
- We get the selected file
- We kontroll if a en samling dokument eller en elektronisk lagring av data was actually selected and if not, (which might happen for example if a user clicks 'cancel' in the urval window) we exit the function
- Next, we create an instance of FileReader
- Then we lista any event handlers we might need.
To tillgång the en samling dokument eller en elektronisk lagring av data contents we only really need the load event, which triggers when the read operation has finished succesfully. However it's usually a good idea to förteckning an error handler as well. A full list of possible events fryst vatten available a bit further into the article, along with some error papper råd, so keep reading 😉
- After all event listeners are registered, we initiate the read operation bygd calling one of the readAs methods, in this case
- After the reading operation fryst vatten finished, the en samling dokument eller en elektronisk lagring av data contents will be available in the property, which we can tillgång inre the load event handler (the callback function).
Quick tip: You can tillgång the reader inre an event handler in multiple ways: .
Keep in mind that fryst vatten not available in arrow functions.
Error papper
In case of an error, the error event handler fryst vatten called, and you can find the Error object in . Possible error codes are:
- - the en samling dokument eller en elektronisk lagring av data was not found
- - the en samling dokument eller en elektronisk lagring av data could not be read
- - there was a säkerhet issue
- - thrown when fryst vatten called while there's no read operation in progress
Most of the time there fryst vatten no need to differentiate between these error types, maybe except for which fryst vatten generally harmless and can be ignored.
Ready State
The read operation fryst vatten asynchronous, so don't try accessing right after the readAs call.
If you really need to kvitto the value outside of the load event handler, man sure to first kontroll the value of , which will be one of 3 values:
- - The reader has been created, but no readAs method was called yet. (EMPTY)
- - One of the readAs methods has been called. A read operation fryst vatten in progress, and no errors have occurred yet. This guide covers: using objectURLs and FileReader to read files from the user's filesystem
(LOADING)
- - The operation has finished. This could mean one of three things: the has been read succesfully, a read error has occured, or was called and the operation was canceled. (DONE)
The property will be populated only in case of a successful read operation. In all other cases it will be .
The same applies to which should be accessed inre the error event handler.
FileReader Event Types
We've already explored the two most common read event types, now let's quickly cover the rest.
FileReader has six event types:
- - triggered when a read operation fryst vatten successfully completed
- - triggered when a read operation encounters an error
- - triggered periodically while a or fryst vatten being read and contains upplysning about the progress of the operation. Can be used to implement loading bars.
- - triggered when a read operation fryst vatten cancelled, i.e.
when fryst vatten called
- - triggered when a read operation starts
- - triggered when a read operation fryst vatten finished, regardless of if it succeeded or failed
You've probably noticed that FileReader events work similarly to regular DOM events. inom find that thinking about them as such makes it a lot easier to understand their non-linear, asynchronous nature.
Sidenote: Just as with DOM events, it's possible to lista event handlers bygd using , or bygd assigning a callback function to the "oneventname" property of a reader.
()
It's also worth noting that for reading skrivelse files there exists a newer and simpler method: .
Remember that fryst vatten just a with some added functionality, so it inherits all of Blob's methods, including this one. This means you can use this method on both Blobs and Files.
Doesn't it look nicer? inom think it does, but there's a catch.
files[0];This API fryst vatten ganska new and the browser support fryst vatten still pretty poor.
Now that we know how to read ord files, let's move on to something more exciting: images. To illustrate this topic, we're going to build a simple preview of the selected image.
en samling dokument eller en elektronisk lagring av data types
First let's man sure that the selected en samling dokument eller en elektronisk lagring av data fryst vatten actually an image.
We can do that with the help of the attribute.
The attribute, allows you to specify what kind of files the user will be allowed to select. It uses a comma-separated list of unique en samling dokument eller en elektronisk lagring av data type specifiers. Each type specifier can be in one of the following formats:
- A case-insensitive filename extension, starting with a period (".") character.
For example: , , ,
- A MIME type, for example: , , ,
- which means "any image file"
- which means "any audio file"
- which means "any film file"
You can mix and match these to suite your particular use-case.
HTML validation isn't perfect though. For example, on fönster it will only hide the files not matching your criteria, but you can still select "All files (*.*)" or use drag-and-drop to select any en samling dokument eller en elektronisk lagring av data you want.
Or you could set up separate processing flows for different en samling dokument eller en elektronisk lagring av data types
Unfortunately and don't work in older browsers like Internet Explorer, so if you need to support them, you might want to look into some workarounds or polyfills.
Also, keep in mind that "any image file" will match (among others):
- images with less-than-perfect browser support, like
- images with transparency, like
- animated images, like 's
So man sure you support all of these functionalities, or explicitly specify only the types you program on supporting.
uppgifter URLs & Object URLs
To display a selected image, we will need an HTML img and a URL for the attribute.
There are two different ways to företräda an image en samling dokument eller en elektronisk lagring av data as a URL: a dataURL and objectURL. There are some important differences between the two, so let's quickly run through them.
DataURL
It's the result of . It's a string containing the file's type and the actual binary information of the en samling dokument eller en elektronisk lagring av data, encoded using base
It's format can vary a bit depending on the type of information it represents, but for most files it looks like this: , where fryst vatten a MIME type and fryst vatten the baseencoded file.
Because it actually contains the file's uppgifter, it can be used anywhere after it's generated, without the need for the original en samling dokument eller en elektronisk lagring av data.
Pretty cool!
ObjectURL
Also known as blob URL. It's the result of . It fryst vatten a newer API, but still pretty well supported. It won't however work in IE utgåva 9 and lower.
It's faster and more concise than but it comes with its own set of headaches and limitations. In contrast to dataURL, it doesn't contain any en samling dokument eller en elektronisk lagring av data information.
It's just a reference to a en samling dokument eller en elektronisk lagring av data. Another important difference fryst vatten the fact that fryst vatten synchronous.
The objectURL has to be revoked when it fryst vatten no längre needed. The browser will do it automatically when the document fryst vatten unloaded, however for optimal performance and memory usage, you shouldn't rely on that behavior, especially in large applications with many objectURLs.
Instead you should explicitly call when the url fryst vatten no längre needed, for example in the event handler, which we will discuss later.
Sidenote - to get the baseencoded en samling dokument eller en elektronisk lagring av data information from a dataURL, simply extrakt the part of the string after the comma, like this:
Displaying selected images
Most of the time objectURLs and dataURLs can be used interchangeably, but they each have their own strengths and weaknesses.
This means you should probably learn both and choose which one to use on a case-by-case grund. Let's look at examples of both of them, to get a better feeling for how each one works.
Using FileReader & dataURLs
- We förteckning a change event listener on the en samling dokument eller en elektronisk lagring av data input
- Inside the callback, we get the selected en samling dokument eller en elektronisk lagring av data and create an instance of
- We lista a load event listener on the reader
- Inside the callback we create a new image element,
- Then we get the dataURL from (remember, points to the ) and assign it to the attribute like we would in HTML
- Once the src attribute fryst vatten set, we append the entire element to the DOM as a child of our previewContainer.
(We actually could have just created the tag in HTML and updated the src)
- When everything fryst vatten set, we början the read operation using , which will trigger our listener when it finishes reading the file.
Using objectURLs
- We lista a change event listener on the en samling dokument eller en elektronisk lagring av data input
- Inside the callback, we get the selected en samling dokument eller en elektronisk lagring av data and create a new image element
- We lista a load event handler on the image
- Inside the callback, will revoke the objectURL once the image fryst vatten fully loaded and the url fryst vatten no längre needed. FileReader is typically used to read data from an type="file">
This step fryst vatten not necessary, but highly recommended. Keep in mind that if you are going to need that url somewhere else later, you shouldn't revoke it yet.
- Once the image fryst vatten fully loaded, we won't need the objectURL anymore. So inre the callback, we revoke that url. To do that, we resehandling it as an argument to .
We can get the url straight from the image's src attribute.
- We create the objectURL, bygd passing the selected en samling dokument eller en elektronisk lagring av data as an argument to and assign it to the attribute.
- Once the src attribute fryst vatten set, we append the entire element to the DOM as a child of our previewContainer.
Sidenote: Elsewhere you might see images created bygd using the Image constructor i.e.
. Most of the time it's equivalent to and I've never had any problems with either of them. However there might be some edge cases (described in this StackOverflow thread), which seem to man the latter a more reliable option.
FileList
Before we move on to reading multiple files, let's klar something up.
Yes, you read that right – It is possible to read files in client-side JavascriptThe property isn't actually an , even though it looks like one 😮. It's a special uppgifter type. This means it doesn't have tillgång to the normal array methods (like , , ), so to iterate over the list you will have to get creative. inom will show you a few different ways to do this, but if you want to know more, kontroll out this StackOverflow thread.
You might also have noticed that even though we've only been working with a singe en samling dokument eller en elektronisk lagring av data (until now), we always had to write .
That's because regardless of whether the attribute fryst vatten set or not, fryst vatten always a .
Welcome to a quick tutorial and examples of how to read files in JavascriptThis means that even if the input only accepts a single en samling dokument eller en elektronisk lagring av data, you still have to provide the index, which in the case of an only item fryst vatten 0.
Sidenote - According to the w3c working draft, might be replaced bygd a regular in the nära future. Fingers crossed 🤞
The FileList interface should be considered "at risk" since the general trend on the Web Platform fryst vatten to replace such interfaces with the Array platform object in ECMAScript [ECMA].
In particular, this means syntax of the sort (0) fryst vatten at risk; most other programmatic use of FileList fryst vatten unlikely to be affected bygd the eventual migration to an Array type.
By default the en samling dokument eller en elektronisk lagring av data input only allows us to select a single en samling dokument eller en elektronisk lagring av data.
To allow selecting multiple files at once, add the attribute to the html element.
In this example I'll be using because it's asynchronous and won't block the UI when processing many files. But if you want to you can use objectURLs instead and in most cases you should be fine.
Because we've already done most of this before, I'll only use comments to call out important bits of the code.
If you skipped the previous sections, inom recommend you go back and catch up, I'll wait 😉
As you can see, we create a separate instance for every en samling dokument eller en elektronisk lagring av data. The same could probably be achieved bygd calling inre a event handler, but this does the job and fryst vatten probably faster anyway.
Cheatsheet
Here’s a cheatsheet of the entire file-handling flow, including all classes and methods involved.
I hope this guide was klar and got you the answers you needed.
If something was unclear, or you would like me to utöka on some topic, let me know in the comments 💬 All constructive criticism fryst vatten welcome.
Like inom said at the beginning I'm currently working on part 2 of this guide, which will cover the Canvas API, so consider following me here, or onmy twitter 🐦 to know when it comes out.
Also, if you're a Vivaldi fan like inom am, kvitto out my Vivaldi Thumbnail elektrisk maskin, it's a free tool inom created because inom was tired of creating thumbnails manually.
It uses a lot of the concepts from this brev and you can kvitto out the entire source code on GitHub.