js to realize the function of uploading pictures

js to realize the function of uploading pictures

The principle of uploading pictures on the front end is: use the input type="file" tag to get the picture, then use the FileReader object to create a new instance, read the picture obtained by the file tag through the readAsDataURL() method of this object and convert it into base64 format, and then transfer it to the background through ajax or other methods after completion.

HTML

You need an input type="file" tag. If you need a preview, you can add an img tag.

<div class="warp">
            <div class="warp-content">Click to upload</div>
            <input type="file" id="file" />
</div>

 
<img src="" />

JS

1. Image uploading requires detecting whether the uploaded image has changed, so here we choose the onchange event of js. First get the dom element of input,img. Under the demo element of input type='file', there is a files attribute, which contains the file information we uploaded. Print it and you can see the name, type and other information of the uploaded file.

var file = document.getElementById('file');
var image = document.querySelector("img");
file.onchange = function() {
    var fileData = this.files[0]; //This is the file we uploaded}

2. Then use the FileReader object. FileReader is mainly used to read file contents into memory. Through a series of asynchronous interfaces, local files can be accessed in the main thread. Using the FileReader object, a web application can asynchronously read the contents of a file (or raw data buffer) stored on the user's computer, and can use the File object or Blob object to specify the file or data to be processed. The readAsDataURL method is used here, which can read the file in base64 format.

How to use

var reader = new FileReader();
reader.readAsDataURL(fileData);//Asynchronously read the file content, the result is represented by the string form of data:url/*Called when the read operation is successfully completed*/
reader.onload = function(e) {
    console.log(e); //Check the object properties. There is a result property. The property value is a long string of base64 format. This is the picture we want. console.log(this.result); //Get the data. Here this points to the instance reader of the FileReader() object.
    image.setAttribute("src", this.result)//Assign a value to the img tag to make it display}

FileReader Object Properties and Events

FileReader object official documentation

3. After completing the second step, we can upload pictures. When users use it again, we cannot guarantee what they upload, pictures or videos. We need to determine the uploaded file type. Under the demo element of input type='file', there is a files attribute which contains the file type information. We can use this attribute to determine the uploaded file type. (In reader.onload, you can get the base64 format of the image through this.result, assign it to a variable and pass it to the backend, thus completing an image upload)

var file = document.getElementById('file');
var image = document.querySelector("img");
file.onchange = function() {
    var fileData = this.files[0]; //Get the first file (File object) in a FileList object, which is the file we uploaded var pettern = /^image/;                
    console.info(fileData.type)

    if (!pettern.test(fileData.type)) {
        alert("The image format is incorrect");
        return;
     }
      var reader = new FileReader();
      reader.readAsDataURL(fileData);//Asynchronously read the file content, the result is represented by the string form of data:url/*Called when the read operation is successfully completed*/
       reader.onload = function(e) {
          console.log(e); //View the object console.log(this.result); //The data you want image.setAttribute("src", this.result)
       }
}

Full code:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style type="text/css">
            .warp {
                display: inline-block;
                vertical-align: bottom;
                position: relative;

            }

            .warp-content {
                border: 1px solid red;
                width: 150px;
                height: 150px;
                line-height: 150px;
                text-align: center;
            }

            input {
                position: absolute;
                top: 0;
                left: 0;
                border: 1px solid red;
                width: 150px;
                height: 150px;
                opacity: 0;
                cursor: pointer;
            }

            img {
                width: 300px;
                height: 300px;
                border: 1px solid red;
                margin-top: 50px;
                vertical-align: bottom;
            }
        </style>
    </head>
    <body>
        <div class="fileBox">
            
            <div class="warp">
                <div class="warp-content">Click to upload</div>
                <input type="file" id="file" />
            </div>

            <img src="" />
        </div>
        <script type="text/javascript">
            var file = document.getElementById('file');
            var image = document.querySelector("img");
            file.onchange = function() {
                var fileData = this.files[0]; //Get the first file (File object) in a FileList object, which is the file we uploaded var pettern = /^image/;
                
                console.info(fileData.type)

                if (!pettern.test(fileData.type)) {
                    alert("The image format is incorrect");
                    return;
                }
                var reader = new FileReader();
                reader.readAsDataURL(fileData);//Asynchronously read the file content, the result is represented by the string form of data:url/*Called when the read operation is successfully completed*/
                reader.onload = function(e) {
                    console.log(e); //View the object console.log(this.result); //The data you want here this points to the instance reader of the FileReader() object
                    image.setAttribute("src", this.result)
                }
            }
        </script>
    </body>
</html>

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • JS implements three methods of uploading pictures and realizing the preview picture function
  • js method to realize the preview of uploaded pictures
  • Upload image preview JS script Input file image preview implementation example
  • WeChat JSSDK upload pictures
  • js to upload pictures and preview them before uploading
  • js implements ctrl+v to paste uploaded pictures (compatible with chrome, firefox, ie11)
  • Javascript verifies uploaded image size [client-side]
  • Realize the function of instant display of uploaded pictures in jsp
  • The restrictions before JS uploads pictures include (jpg, jpg, gif, size, height, width), etc.
  • js upload image preview problem

<<:  Some improvements in MySQL 8.0.24 Release Note

>>:  Web designer's growth experience

Recommend

Solve the problem that Docker pulls MySQL image too slowly

After half an hour of trying to pull the MySQL im...

MySQL 8.0 installation tutorial under Linux

This article introduces how to install MySQL 8.0 ...

Solve the black screen problem after VMware installs Linux system and starts

1. Installation environment 1. HUAWEI mate x cpu ...

Implementation of Nginx filtering access logs of static resource files

Messy log Nginx in daily use is mostly used as bo...

Vue advanced usage tutorial dynamic components

Table of contents Basic description AST parsing R...

Introduction to JavaScript Number and Math Objects

Table of contents 1. Number in JavaScript 2. Math...

MySQL SHOW PROCESSLIST assists in the entire process of troubleshooting

1. SHOW PROCESSLIST command SHOW PROCESSLIST show...

How to implement encryption and decryption of sensitive data in MySQL database

Table of contents 1. Preparation 2. MySQL encrypt...

About the usage and precautions of promise in javascript (recommended)

1. Promise description Promise is a standard buil...

Detailed example of inserting custom HTML records in Quill editor

It is already 2020. Hungry humans are no longer s...

Pitfalls and solutions encountered in MySQL timestamp comparison query

Table of contents Pitfalls encountered in timesta...

JavaScript array reduce() method syntax and example analysis

Preface The reduce() method receives a function a...