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

Instructions for using MySQL isolation Read View

Which historical version can the current transact...

Detailed steps to deploy SpringBoot projects using Docker in Idea

Preface Project requirements: Install the Docker ...

Tutorial on using the hyperlink tag in HTML

The various HTML documents of the website are con...

mysql5.6.8 source code installation process

Kernel: [root@opop ~]# cat /etc/centos-release Ce...

A complete list of commonly used MySQL functions (classified and summarized)

1. Mathematical Functions ABS(x) returns the abso...

The use of MySQL triggers and what to pay attention to

Table of contents About Triggers Use of triggers ...

How to use jconsole to monitor remote Tomcat services

What is JConsole JConsole was introduced in Java ...

Examples of importing and exporting MySQL table data

This article describes the import and export oper...

JavaScript to implement login slider verification

This article example shares the specific code of ...

Description of the execution mechanisms of static pages and dynamic pages

1. A static page means that there are only HTML ta...

React concurrent function experience (front-end concurrent mode)

React is an open-source JavaScript library used b...

react-diagram serialization Json interpretation case analysis

The goal of this document is to explain the Json ...

Some "pitfalls" of MySQL database upgrade

For commercial databases, database upgrade is a h...

Detailed explanation of the 4 codes that turn the website black, white and gray

The 2008.5.12 Wenchuan earthquake in Sichuan took...