It has been nearly one and a half months since my last blog post. I feel a little irritable and can’t settle down to study. I don’t know why. Maybe it’s hot, a little restless. Last week, I saw Nezha and the new Spider-Man: Far From Home. I was so excited to see the shadow of Iron Man in Peter Parker.

demand

Why did I think of writing this blog preview of local files today, because I encountered problems at work 😅😅😅

  1. You need to upload pictures
  2. Images need to be displayed before they can be uploaded
  3. The previous image uploading implementation is to return the URL after uploading successfully, and then show the image according to the URL

That’s what needs to happen now. In order to do this, I currently feel that I have to have a preview of the local images on the page, because the images are not uploaded at the time of display, and there is no such thing as an image address

A search on the Internet, as expected html5’s powerful embodiment, there is a native API can achieve ————FileReader.

FileReader method

The FileReader instance has four methods, three for reading files and one for interrupting reads (I haven’t used this method yet 😃 no need ~). It is important to note that these methods do not return the read result directly, regardless of whether the read succeeds or fails. Instead, they return the read result in the result attribute (described later).

  1. abortMethod, parameternone, terminal read
  2. readAsBinaryStringMethod, parameterfile, reads the file as binary code
  3. readAsDataURLMethod, parameterfile, read the file as DataURL
  4. readAsTextMethod, parameterfile, [encoding], reads the file as text

ReadAsText: This method takes two arguments, the second of which is the encoding of the text. The default value is UTF-8. This method is very easy to understand. It reads the file as text, and the result is the contents of the text file.

ReadAsBinaryString: This method reads the file as a binary string, which we usually pass to the back end, which can store the file from this string. (The following is not used… Awkward…)

ReadAsDataURL: This method reads a file as a string beginning with data:. The essence of this string is data URL. DataURL is a scheme to embed small files directly into documents. Small files here usually refer to files in the format of images and HTML. (The image is converted to base64 format)

FileReader event

FileReader has an event model that provides the entire process, allowing you to do whatever you want at each stage of reading a file

  1. onabortIs triggered when an interrupt occurs
  2. onerrorIs triggered when an error occurs
  3. onloadTriggered when the file read completes successfully
  4. onloadend, read completion triggers regardless of success or failure
  5. onloadstartTriggered when the read starts
  6. onprogressTo read the

The basic process is onloadStart > onProgress > onLoad > onloadEnd

Let’s use

readAsDataURL

So let’s go directly to the code ⬇️

<input type="file" id="file">
<img src="" alt="" id="img">
Copy the code

All we need now is for the image we selected from the tag to be displayed without request in the tag below

let reader = null; // Declare the reader variable for later use

const fileNode = document.querySelector('#file'); // Get the input tag

fileNode.addEventListener('change', (e) => { // Add an event listener for the fetched input tag, fired when the file is selected
  if (window.FileReader) { // Check whether you have FileReader in your browser. Not all browsers have FileReader now
    reader = new FileReader(); // instantiate FileReader
    reader.onload = (event) = > { // Sets the method to execute after a successful read
      document.querySelector('#img').src = event.target.result; // As mentioned earlier, the data returned successfully is placed in the result attribute, which is then set to the SRC address of the IMG tag}}else { // No FileReader pop-up warning and return
    alert('Your browser doesn't have FileReader, you can't do that! ');
    return;
  }
  const file = e.target.files[0]; // Get the selected file information
  reader.readAsDataURL(file); // Convert the file information to the DataUrl and execute the reader.onload method
})
Copy the code

This way we can view images locally without uploading them!

So far, we’ve used the readAsDataURL method and the onLoad event, and now let’s look at readAsText, which is reading text.

readAsText

Again, let’s change the HTML first

<input type="file" id="file">
<div id="text"></div>
Copy the code
let reader = null; // Declare the reader variable for later use

const fileNode = document.querySelector('#file'); // Get the input tag

fileNode.addEventListener('change', (e) => { // Add an event listener for the fetched input tag, fired when the file is selected
  if (window.FileReader) { // Check whether you have FileReader in your browser. Not all browsers have FileReader now
    reader = new FileReader(); // instantiate FileReader
    reader.onload = (event) = > { // Sets the method to execute after a successful read
      document.querySelector('#text').innerHTML = event.target.result; // As mentioned earlier, the successfully returned data is added to the result attribute, and the returned text is added to the specified tag}}else { // No FileReader pop-up warning and return
    alert('Your browser doesn't have FileReader, you can't do that! ');
    return;
  }
  const file = e.target.files[0]; // Get the selected file information
  reader.readAsText(file); // Convert file information to text. The default format is UTF-8
})
Copy the code

Create a TXT file, other text files should also work

This allows us to preview images and text locally

relax

To extend this, when we fetch an image, we actually convert it to base64 and render it on a page. We now have an API that generates a local address for the image and renders it, url.createObjecturl ().

How does it work?? Let’s look at the code

This time our HTML has two IMG tags for comparison

<input type="file" id="file">
<img src="" alt="" id="img">
<img src="" alt="" id="img2">
Copy the code
let reader = null; // Declare the reader variable for later use

const fileNode = document.querySelector('#file'); // Get the input tag

fileNode.addEventListener('change', (e) => { // Add an event listener for the fetched input tag, fired when the file is selected
  if (window.FileReader) { // Check whether you have FileReader in your browser. Not all browsers have FileReader now
    reader = new FileReader(); // instantiate FileReader
    reader.onload = (event) = > { // Sets the method to execute after a successful read
      document.querySelector('#img').src = event.target.result; // As mentioned earlier, the data returned successfully is placed in the result attribute, which is then set to the SRC address of the IMG tag}}else { // No FileReader pop-up warning and return
    alert('Your browser doesn't have FileReader, you can't do that! ');
    return;
  }
  const file = e.target.files[0]; // Get the selected file information

  CreateObjectURL () */

  document.querySelector('#img2').src = URL.createObjectURL(file) CreateObjectURL () converts file information to a URL directly using url.createObjecturl ()

  /* end */
  reader.readAsDataURL(file); // Convert file information to DataUrl
})
Copy the code

conclusion

Now we can implement local preview of images, text, and the need to generate urls for preview.

In the future, I will continue to update my blog to record the small problems AND new skills I have learned


I’m a front end warrior, a front end elementary school.