The binary used by the frontend

In fact, the front-end often involves the concept of binary streams. Think carefully about uploading and downloading files, uploading and displaying pictures, whether you have heard of blob, arrayBuffer, fileList, file, and base64 but have never thought about them carefully. the difference. What are these and how are they used?

1.blob,FileList,File

File upload is a common front-end function. Before performing the function, you should understand a few concepts (don’t be intimidated by these professional rankings, you will find it is very simple after reading it carefully)

blob

MDN's explanation of blobs -  Blob - Web API Interface Reference | MDN

Blob is a file-like object, not necessarily the native data format of JavaScript. The name comes from the SQL database and represents a binary large object. On the front end blobs are binary objects dedicated to backing files (use read, not modify, data immutable)

FileList

MDN's explanation of FileList - FileList - Web APIs | MDN

FileList is to use the input box to select the uploaded file and return the file list

File

MDN's explanation of file -  https://developer.mozilla.org/en-US/docs/Web/API/File

The file object is a file object in the FileList

file is a file that inherits blob and extends to support user system ( File object is a special type of blob )

Select a document

Remember how to use native upload files? What is the format of the uploaded file?

First print the output to see what the file looks like in our eyes

<body>
    <div id="test">
        <input type="file" id="file">
    </div>
    <script>
        let fileDom = document.getElementById('file');
        fileDom.addEventListener('change', function(e) {
           console.log(fileDom.files)
           console.log(fileDom.files[0].arrayBuffer())
        })
    </script>
</body>

look at the output


The printout verifies the previous concept

The data obtained by input is a FileList file object, and each file object File is inside. To see the file, use arrayBuffer() to view it                   

After the file is uploaded, let's take a look at the mutual conversion through the image upload echo

    <input type="file" id="file">
    <div id="imgbox"></div>
    <script>  
        document.getElementById('file').onchange = function(e) {
            document.getElementById('imgbox').innerHTML = `<img src=${URL.createObjectURL(e.target.files[0])}>`       
        }
    </script>

   Open the console and have a look

                                                                                                                                                                                                    If you want to display the obtained file object in the picture, you can use URL.createObjectURL(blob) to convert it into an address that can be parsed by the img tag. You can see the beginning of the address blob:// src can not only parse blob but also base64,                                                                                                     then What is base64?

 base64                    

 Base64 - MDN Web Docs Glossary: Definitions of Web-related terms | MDN

 

 src can parse base64, the common one is blob to base64, base64 to blob

    <input type="file" id="file">
    <div id="imgbox"></div>
    <script>  
        //blob转base64
        function blobToDataURL(blob) {
            return new Promise((reslove, reject)=> {
                var reader = new FileReader();
                reader.readAsDataURL(blob); // 读取文件
                reader.onload = function (e) {
                    reslove(e.target.result)
                }
            })
            
        }

        document.getElementById('file').onchange = function(e) {
            blobToDataURL(e.target.files[0]).then(res => {
                document.getElementById('imgbox').innerHTML = `<img src=${res}>`
            })
            
        }
    </script>

blob to base64

function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);

    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}

You can get blob data through file.fileList. Blob data is an object type of js that can store a large amount of binary data. There is no introduction to the properties and methods of blob here. If you want to know more, you can check it on mdn

Careful students may find that a fileReader function is used in the conversion above. FileReader can asynchronously read the stored files on the computer. I won’t introduce it here, because mdn is also very detailed. If you are interested, you can read it by yourself.

In addition to image echo, blob can also download files

let blob = new Blob(['我是文件'])
let url = URL.createObjectURL(blob);
let a = document.createElement("a");
a.download = '文件.text';
a.href = url;
document.body.appendChild(a);
a.click();
a.remove();

Let's use a picture to summarize the above knowledge points

Guess you like

Origin blog.csdn.net/qq_42625428/article/details/123185568