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

Summary of MySql import and export methods using mysqldump

Export database data: First open cmd and enter th...

Issues with upgrading Python and installing Mongodb drivers under Centos

Check the Python version python -V If it is below...

How to use explain to query SQL execution plan in MySql

The explain command is the primary way to see how...

HTML Tutorial: Collection of commonly used HTML tags (5)

These introduced HTML tags do not necessarily ful...

Native JS to achieve book flipping effects

This article shares with you a book flipping effe...

JavaScript object built-in objects, value types and reference types explained

Table of contents Object Object Definition Iterat...

CSS overflow-wrap new property value anywhere usage

1. First, understand the overflow-wrap attribute ...

A brief introduction to Linux environment variable files

In the Linux system, environment variables can be...

Solve the error during connect exception in Docker

When you first start using Docker, you will inevi...

Simple implementation of vue drag and drop

This article mainly introduces the simple impleme...

Sample code for a simple seamless scrolling carousel implemented with native Js

There are many loopholes in the simple seamless s...

18 common commands in MySQL command line

In daily website maintenance and management, a lo...