Read a file using the FileReader API – JavaScript Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome to this video tutorial so what i'm going to be showing you today is how you can read files into front-end javascript using the file reader api this allows you to display the contents of a file to a user and also edit a file without the need to contact a backend server so i already have some files here that i'm going to be reading in the first is this beach image i'm going to be applying a filter to this and then sending it to a server the next one is this spreadsheet so this is a standard csv file i'm going to read this in and then turn it into a html table but we're going to begin with a very simple example which is this text file containing some standard lorem ipsum text so i'm going to show you how you can preview that in the browser so in my html i've already created an input element of type file and that's going to allow user to select a file from their system and also a div with an id of preview where i'm going to be displaying the contents of the various files that i'll be reading in and in my script i've already selected both of those elements now the way that files are going to be read in is they're going to be user selected the user is going to select them using this input element and i want the file to be read every time the user selects a file so the first thing i'm going to do is to add an event listener to the file input element and the event i want to listen out for is change so every time user selects a file this associated function is going to fire and it's in this function that i'm going to do the reading in of the file okay so to read in a file the first thing you want to do is to create a new file reader so the way that you do that is you type the new operator before the file reader object constructor and that's going to create a new object of its type so a new file reader object which i will save in a variable fr so this file reader object we've just created it contains all the methods that we need to be able to read files into javascript now the first file i'm going to be reading in here is this text file so i'm going to select the method on the new file reader read as text now i will be using the other method read as data url when i read in beach.jpg because in that case i'm going to want to create a url that i can use to set the source of an image element but let's continue now with this example of the text so the next thing i need to specify is the location of the file that i want to read so it's a user selected file so it's going to be available on file input now a user selected file it's available on the files property and it's stored there in an array just in case a user uploads multiple files which is possible in some cases but in this case it's just a single file so we're selecting the file at position 0. so this is now going to read a file as soon as the user selects one from their system but it takes a little bit of time for this to happen therefore you need to add an event listener to the file reader object and you're listening out for a load event so when that occurs that is to say when the file reading has finished then this function will run and the result of the file reading is available on the result property on the file reader so to preview the contents of the text file in the dom i'm going to set the text content of the preview element already in my html as the result of the file reading so let's check if it's working head over to the browser select the text so obviously the file reading was successful and the result has been written here to the dom so this kind of file reading could be useful if you want a user to be able to preview the contents of a file that they've selected before it's sent to a server or if you are creating a translation app or a spellcheck app and you want the user to be able to read in some text that's already on their system without having to copy and paste the text into their browser okay so that's how you read in a basic text file let's move on to a different type of file now i'm going to read in this spreadsheet here dot csv file so what i'm going to do is first of all read in the file then i'm going to convert the data into an array then i'm going to write the data in that array into a html table so this is going to be an example of a basic csv to html table app and at the end the user will be able to download the code so they can use it in their own project so a csv file is just a type of text file so i'm not going to need to change the method i'm using to read it in and i'm still going to be reading the user input file from the file input element but what i am going to want to do is to manipulate the result this time so that the user doesn't just see a preview of the text in this csv file but in the end they see a html table containing the data of the csv that they selected so first of all i'm going to save the result of the reading in a new variable so i'm going to call that csv so the first thing i need to do to convert the data from csv text format to javascript array format is to split the text every time there is a new line now the encoding in windows for a new line it is backslash r backslash n in mac i think it's different i haven't tested it on a mac here but i'm just going to stick with this in this tutorial because this is the encoding that is used on my system if you're going to publish an app like this obviously you want to check that before deploying it so now that i've split the text by new line so each line is in its own array i want to split the data in each line by the comma that is separating each bit of data so to do that i want to iterate through each line of the data and i actually want to split again but this time i'm splitting by comma and in order to get an array back i need to make the result of that the return value of map i'm going to save that in a new variable called array and check it's all working i'm going to log the value returned by mac to the console so i will feed in the csv file now in the console you see there are six arrays and each of those arrays contains three items so each of the items in the nested arrays are the bits of data and the six arrays at the top level are the lines of data so depending on your use case you might want to stringify this data now and send it to a server but what i'm going to be doing is going one step further in the browser writing this data to a html table and then making the html code available to the user so that they can then use it in their own project and the great thing is that there's no need to contact a server the user uploads it and the editing is happening all inside the user's browser so to create a html table of course the first thing i need to do is to create a table element into which i'm going to be inserting rows and data so what i want to do is to iterate through each line of data so to do that i call for each on the array so each of the arrays is a line and for each line i'm going to create a table row element that i'm going to append into the table that i created so to access the data itself i want to iterate through each line so i'm going to use for each again so first thing i want to do in here is to create a table data element and i want to make the text inside each table data element the content of the cell that i'm iterating through now i'm ready to append that cell to its table row i want to append the table row complete with cells to the table and after all table rows have been appended to the table i want to append the table into the preview element in the dom okay so let's see how that looks in the dom select my spreadsheet again and now you see that the csv data is being written to this html table now i actually want to make a change to the table because this top row the data here should be inside table header elements and not table data elements so i can make a modification here in my code so for this i'm going to need to know the index of the line so this is available to me as a second parameter in the top four each where i'm appending the rows and now in this for each where i'm appending the cells i'll make an if statement and i'll say if index is equal to zero so if it's the first line then i want table data to equal th table header otherwise i want it to be table data like it was before and i still need to declare the table data variable up here so let's check if that's fixed the issue reload the spreadsheet and now you can see the difference so the data in the top row is being embedded in table header elements so inside this first row table header and then in the rest table data okay so to complete the project and return the code used to create this table to the user what you want to do is to take the inner html out of the preview element containing the table so i'm going to create a new variable html and that's going to store preview dot in html so i'm going to write that text into a code element and for standalone code it's best to embed it inside a pre element so i will create both of those now now i want to write that markup inside the code element so i don't use in html for that because i don't want the markup to be rendered as html i just want it to be rendered as text so for that i'll use inner text and finally i want to append the code element inside the pre element and then the pre element to the dom so now when i feed in the csv file the code used to create the table should appear below it as text so you see the code is there below it but it's not really in the format that you would want if you copied and pasted it you could recreate the table so the two scripts you need are standalone.js which is the main package so i'll add that now in the head of my document and you also want html min.js put that below in the head of your document and then you can use that to pass the markup that we had and prettify it so to use it you need to access the prettier object that now exists that has a method on it called format and you want to pass the html value into there and then you need to set a couple of options as an object in the second position so the first thing you need to specify is the parser so in this case it's html you need to specify that because prettier can be used for other languages and second you need to ensure that you include a second property called plugins and set the value of that to prettier plugins so hopefully the library is now doing its magic and converting that single line of html that was being returned before into a nicely formatted bit of code there it is there so very human readable now so using the file reader in this instance we've created a basic csv to html table app and the great thing is that we did all of the main processing without contacting our own server it's all happening inside the user's browser of course we did contact a cdn to prettify the code but the main processing was done in the browser now finally i'm going to be showing you how you do something similar for an image so i'm going to be applying some filters to this beach.jpeg file now inside my code i can delete most of this because obviously i'm not going to be doing any of the processing that i was for the table and i also want to delete this csv variable but the result's still going to be on the result property on the file reader now the big difference with an image file is you don't want to read it in as text instead you want to create a data url that you can use to set the src of an image element in the dom so i'll set this to read as data url so the result is going to be a url containing the data and i'll just log that to the console so you can see what that looks like because it doesn't look like a typical url now i'm ready to read the file in so you see here that you get a very very long url that starts with data colon image forward slash jpeg so it's detected the type of file that it is and then this very very long url describes this image so you can see that it's 55 kilobytes if i copy that and try to access that url in a new window you see that i still get the image the image is fully described in the data url now in javascript you can use it just like a regular url to set the src of an image so i'm going to create a new image here in javascript so you can do that with the image constructor object and want to set the src to url and finally append that image element to the preview element so now when i select the image from file it should now appear on screen so clearly that is now working now to apply a filter to this image i can use the native html canvas api in javascript but the first thing i need to do before i start using it is wait for the image to load before i start trying to process the image so the first thing to do is to create a new canvas element next i need to get a context for the canvas to draw on so for that i'm going to use a standard 2d context now i set the width and height of the context to that of the image that has loaded so that information is now available next you want to draw onto the context from the canvas that you've created and you do that with the draw image method on context now inside of draw image you want to first of all specify what it is you want to draw so in our case it's image and then the point on the x and then the y axis where you want to start drawing so to start in the extreme top left hand corner you specify zero zero now to see the result i'm going to append the canvas to the dom so i'll say preview dot append child and i'm appending the canvas and i will get rid of this line of code here where i'm appending the image element to the dom so let's take a look at the results so far i select my image now it looks pretty much the same as before the difference is that this is now in a canvas element and i've drawn this to the dom now because i've done it this way i can now use the html canvas api to add a filter to this image so just before i draw the image i'll add a filter and i'll set the filter to grayscale now you enter a number between zero and one here representing how much of a grayscale you want to apply so for example 0.5 it's going to be half grey scaling if i entered one you would get complete grayscaling now there are other filters available so if you want to add some blur you can do so like this so it's a little bit blurred there you can also add saturation so a value of one here will return the image with a regular level of saturation if i set it to zero it's going to remove all saturation from the image so it's grayscale again if i go for value of two then we're going to see an extremely highly saturated image sorry i have to refresh again there there you go something else you might be interested in doing is adding some text to the image so you can do that after you've drawn the image using the fill text method so the first argument you pass in is the text you want to write so wish you were here and then the next arguments are where you want to draw it on the x-axis and the y-axis so i want a little bit of space from these sides now the text will appear on the image but the text is very small so i will need to set the font here so i can do that by saying ctx font and i'll set that to 60px serif and that will hopefully look a little bit better there so it's a bit too tight at the top there so let me change the y-axis value to 90. so in this way you can create an app that can turn a user-selected image into a postcard or whatever you like now something you might want to do next is to send this image that you've edited in the user's browser to your server so i'll show you how to extract the image from the canvas now so that you can send it to the server in http request so i'm going to make the request here in the code just after i've edited the image so the way you can extract an image from a html canvas is to say to canvas. so in case you're not aware blob stands for binary large object it's a very common way to store a file so that you can send it to a server also outside javascript so it's a universally recognized format and the parameter you have available to you here is the blob itself now an easy way to send a blob in a request is to attach it to a form data object so there's no form here but nevertheless i'm going to create a new form data object and the reason that this is useful is because a form data object will automatically detect its contents and set the request headers for you so the way that you append something to a form data object is to call the append method on it and then you need to give your file a name so i'll call this image then the file itself which is a blob and then you can give the file a name so i will call this image.png now i'm going to send the file to a server using fetch so i'm going to send it to an endpoint here that i like to use for testing it's called httpbin.org and it's post request so you send it to the post endpoint now by default fetch is going to make a get request so i need to set an object here specifying that the method is going to be post and i also want to attach the payload to the request which is form data so fetch is promise based and to read the result of a promise you use special then syntax so the first thing you get back is just a readable stream not payload so to process that you have to call res.json the result of reading that stream is going to be available in the next then statement and this time i do get the payload so i'm going to log that to the console so because this server mirrors back whatever you send it if it was successful we should see in the payload in the response the image that we sent to the server so the request will be made as soon as i load the image let's wait for the response a moment because obviously we've got an image attached so it might take a little bit of time so let's inspect what we got back from the server so you can see in the headers these were set for us there's quite a lot of headers there that's because we embedded the payload in a form data object so that's why it was useful to use that and here in the files property it looks like we have the image available to us so just to check that everything worked as expected i'm going to copy its contents into a new window and hopefully it renders as the image that we created so with the text with the csv and now with the image we're able to read a file into front-end javascript and manipulate it without having to contact our server so that is it for this tutorial on the file reader api i hope you found it useful if you did please consider hitting the like button down below this video and if you'd like to see more content like this don't forget you can subscribe to the channel
Info
Channel: OpenJavaScript
Views: 18,318
Rating: undefined out of 5
Keywords:
Id: u2VTtAXq1iA
Channel Id: undefined
Length: 25min 48sec (1548 seconds)
Published: Sat Sep 17 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.