This article was originally published on the public account CoyPan as expected

Writing in the front

In front-end development, we often encounter operations on files, especially images. On the Node side, file interfaces are provided for us to use. In the browser, Html5 provides a File-related Web Api.

This article briefly summarizes how to use the file-related API to manipulate files and some related knowledge.

The File object

A File object contains the following attributes:

LastModified: read only. The file was last modified (UNIX timestamp). Name: read only. File name (excluding the full path). Size: read only. File size. Type: read only. The MIME TYPE.Copy the code

Look at an example:

In the browser, we can also use the File constructor directly to construct an instance of a File object.

var json = `{ "a": 1 }`;
var f = new File([json], 'test.json', {
    type: 'application/json'
});
console.log(f);
Copy the code

The contents of a File object can be of many data types, including ArrayBuffer, ArrayBufferView, Blob, and DOMString (in JS, DOMString is String). This article does not go into further details.

How do I get a File object

So, how do you get a file object? As mentioned above, we can use the File constructor directly. Most of the time, we want to let the user select, and in this case, we need to use the input tag. The code is very simple, we just need to set the type of the input tag to file.

<html>
    <input type='file'/>
    <script>
        const el = document.querySelector('input');
        el.addEventListener('change', e=> {
            const fileList = e.target.files;
            [].slice.call(fileList).forEach(file= > {
                console.log(file);
            });
        });
    </script>
</html>
Copy the code

We just need to listen for the change event on the input tag to get the file object. The thing to notice here is that what we’re actually getting is a list of files, and the list of files is an array-like object that needs to be converted to an array in order to be traversed exactly like an array.

If you want to select multiple files, add the multiple attribute to the input tag. If only certain types of files are accepted, you can add the Accept attribute.

 <! -- Select multiple files -->
<input type='file' multiple />

<! -- Multiple options, can only select image files -->
<input type='file' multiple accept='image/*'/>
Copy the code

As you can see in the figure above, using the input tag directly is not pretty. We can do this by hiding the input tag and using code to trigger the click event for the input tag.

<html>
    <input type='file' style="display:none"/>
    <button>This is a cool button</button>
    <script>
        const inputEl = document.querySelector('input');
        inputEl.addEventListener('change', e => {
            const fileList = e.target.files;
            [].slice.call(fileList).forEach(file= > {
                console.log(file);
            });
        });   
        const btnEl = document.querySelector('button');
      	btnEl.addEventListener('click', () => {
          	inputEl.click();
        });
    </script>
</html>
Copy the code

How do I read the contents of a File object

How to get a file object, so how to read the contents of the file? At this point, you’ll need another Web Api: FileReader

Using FileReader to read file contents, the main steps are as follows:

// declare an instance of the FileReader object
var fileReader = new FileReader();

// 2
fileReader.onload = function(e) {
  const result = e.target.result;
}

// 3. Read the file contents
// Where file is a file object.
fileReader.readAsDataURL(file); // Read base64

/ / fileReader readAsArrayBuffer () to read ArrayBuffer
// filereader.readastext () is read as a string
Copy the code

A common scenario is to read a local image and display a thumbnail. It’s very simple to implement.

<html>
    <input type='file' accept='image/*' />
    <script>
        const el = document.querySelector('input');
        el.addEventListener('change', e=> {
            const imgFile = e.target.files[0];
            const reader = new FileReader();
            reader.onload = function(e) {
            	const base64 = e.target.result;
            	const imgEl = new Image();
            	imgEl.src = base64;
            	imgEl.onload = function() {
            		document.body.appendChild(imgEl);
            	}
            }
            reader.readAsDataURL(imgFile);
        });
    </script>
</html>
Copy the code

Want to file in a browser preview, there is another method: using the window. The URL. CreateObjectURL

Window. URL. CreateObjectURL can accept a file object as a parameter, returns a string. This string is a string containing an object URL that can be used to specify the contents of the source file object. Look at the following example:

<html>
    <input type='file' accept='image/*' />
    <script>
        const el = document.querySelector('input');
        el.addEventListener('change', e=> {
            const imgFile = e.target.files[0];
            const imgSrc = window.URL.createObjectURL(imgFile);
            console.log(imgSrc);
            const imgEl = new Image();
            imgEl.src = imgSrc;
            imgEl.onload = function() {
                document.body.appendChild(imgEl);
                window.URL.revokeObjectURL(imgFile); }});</script>
</html>
Copy the code

As you can see, SRC in this image is a string that begins with blob:. This is a protocol implemented by the browser itself. It refers to a reference to a resource that must be mounted to a resource object (such as IMG or video) in a web page to display it.

How do I download a custom File from a page

The following scenario is common: generate a custom file on the page and then download it. To implement this requirement, follow the following line of thought:

  1. Start by generating a file. As mentioned earlier, we can construct a File directly using new File.
  2. Generates a reference to the file. Can use window. URL. CreateObjectURL to create a reference to a file.
  3. Download. Use the A tag to set the Download property.

Code examples:

<html>
    <button>Click on the download</button>
    <script>
        const btnEl = document.querySelector('button');
        btnEl.addEventListener('click'.function() {
            const json = `{ "a": 1 }`;
            const file = new File([json], 'test.json', {
                type: 'application/json'
            });
            const url = window.URL.createObjectURL(file);
            const aTag = document.createElement('a');
            aTag.href = url;
            aTag.download = 'test.json';
            aTag.click();
        });
    </script>
</html>
Copy the code

Write in the back

This paper mainly introduces how to deal with File in the front-end page. File objects inherit from BLObs. File is a special Blob. Blob is short for Binary Large Object, an immutable, raw data-like file Object used to process Binary data. For details on this section, please refer to this article.

In addition, the latest version of Chrome already supports reading and writing local files directly. Am I