How does js read the file when uploading the file?

Table of contents

1. Upload function realization

2. Read the uploaded file

3. Complete code demo


1. Upload function realization

The first step is to use the input tag and set the type to type="file"

The second step is to set the change event for the input, and get the uploaded file through target.file in the callback function of the response

Note: Because the default style of the input is ugly, when we usually develop, we usually hide the input button, and then write a button of our own. When clicking the button we set, just give the default input a click.


2. Read the uploaded file

The core api that implements this function is FileReader()

By instantiating FileReader(), you can get the specific content of the uploaded file

 reader.onload = function () {
                  console.log(reader.result,'reader');//文件结果
                }
                 reader.readAsText(File) //作为txt

3. Complete code demo

It can be opened directly for testing.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="file" onchange="upload()"></input>
    <script>
    function upload(event) {
                var e = window.event||event;
                console.log(e)
                // 获取当前选中的文件
                var File = e.target.files[0];
                console.log(File,'获取当前选中的文件');//打印值看下面图片,简单点的话我们直接把这个数据给后台处理就可以了
                let reader = new FileReader()
                //将上传的文件读取成text
                reader.onload = function () {
                  console.log(reader.result,'reader');
                }
                 reader.readAsText(File)
            }
    </script>
  </body>
</html>

Guess you like

Origin blog.csdn.net/wanghaoyingand/article/details/130320342