html+css+js to realize the function of photo preview and upload picture

html+css+js to realize the function of photo preview and upload picture

Preface: When we are making web pages, we often need to upload pictures, which may be to select pictures or take photos to upload. Although the simple use of <input type="file"/> can also achieve the function, the user experience may be a bit worse. Therefore, this article records the use of css+js to achieve the preview and compression upload functions after the picture is selected. Some of them come from the Internet and are recorded and sorted here.

Effect preview:

1. Create index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
        <title>Photo Upload</title>
        <link rel="stylesheet" href="index.css"/>
        <script type='text/javascript' src='index.js' charset='utf-8'></script>
    </head>
    <body>
         <form id="mainForm">
            <div class="content">
                <div class="label">ID card</div>
                <div class="img-area">
                    <div class="container">
                        <input type="file" id='id-face' name='face' accept="image/*" />
                        <div id='face-empty-result'>
                            <img style='width:4rem' src="https://github.com/wangheng3751/my-resources/blob/master/images/camera.png?raw=true" alt="">
                            <p>Front photo of ID card</p>
                        </div>
                        <img style='width: 100%' id='face-result'/>
                    </div>
                    <div class="container" style='margin-top:0.5rem;'>
                        <input type="file" id='id-back' name='back' accept="image/*" />
                        <div id='back-empty-result'>
                            <img style='width:4rem' src="https://github.com/wangheng3751/my-resources/blob/master/images/camera.png?raw=true" alt="">
                            <p>Photo of the back of your ID card</p>
                        </div>
                        <img style='width: 100%' id='back-result'/>
                    </div>
                </div>
            </div>
            <div class="btn">
                Submit</div>
         </form>
    </body>
</html>

2. Create index.css

body{
    margin: 0
}
.content{
    padding:0.5rem;
    display: flex;
    align-items: center;
    border-bottom: 1px #999 solid
}
.label{
    width:5rem;
}
.img-area{
    flex:1
}
.container{
    background-color:#e7e7e7;
    position: relative;
}
.container div{
    text-align: center;
    padding:0.5rem 0
}
.container input{
    opacity:0;
    filter:alpha(opacity=0);
    height: 100%;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 9;
}
.container p{
    font-size: 0.9rem;
    color:#999
}
.btn{
    background-color: #4363ab;
    color: #fff;
    text-align: center;
    padding: 0.5rem 1rem;
    width:80%;
    border-radius: 0.2rem;
    margin: 2rem auto;
    font-weight: 600;
    font-size: 1.2rem
}

3. Create index.js

window.onload = function(){
    document.getElementById("id-face").addEventListener("change", function(){       
        onFileChange(this,"face-result","face-empty-result")
    });
    document.getElementById("id-back").addEventListener("change", function(){       
        onFileChange(this,"back-result","back-empty-result")
    });
    document.getElementsByClassName("btn")[0].addEventListener("click", function(){       
        submit();
    });
};
/**
 * Processing when an image is selected* @param {*} fileObj input file element* @param {*} el //The element ID used to display the image after selection
 * @param {*} btnel //Button area ID displayed when the image is not selected
 */
function onFileChange(fileObj,el,btnel){
    var windowURL = window.URL || window.webkitURL;
    var dataURL;
    var imgObj = document.getElementById(el);
    document.getElementById(btnel).style.display="none";
    imgObj.style.display="block";
    if (fileObj && fileObj.files && fileObj.files[0]) {
        dataURL = windowURL.createObjectURL(fileObj.files[0]);
        imgObj.src=dataURL;
    } else {
        dataURL = fileObj.value;
        imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
        imgObj.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;
    }
}
/**
 * Compress the image and return the data in base64 format* @param {*} image img element* @param {*} width width of the compressed image* @param {*} height height of the compressed image* @param {*} qua //Image quality 1-100
 */
function compressImageTobase64(image,width,height,qua){
    var quality = qua ? qua / 100 : 0.8;
    var canvas = document.createElement("canvas"),     
        ctx = canvas.getContext('2d');     
    var w = image.naturalWidth,     
        h = image.naturalHeight;     
    canvas.width = width||w;     
    canvas.height = height||h;     
    ctx.drawImage(image, 0, 0, w, h, 0, 0, width||w, height||h);
    var data = canvas.toDataURL("image/jpeg", quality);     
    return data;
}
//Submit function submit(){
    //1. Form submission//document.getElementById("mainForm").submit();
    //2. Ajax submission after compression var face_data=compressImageTobase64(document.getElementById("face-result"),200,100,90);
    var back_data=compressImageTobase64(document.getElementById("back-result"),200,100,90);
    var formData = new FormData();  
    formData.append("face",face_data);
    formData.append("back",back_data);
    //Need to introduce jQuery
    $.ajax({
        url:"/address",
        type: 'POST',
        cache: false,
        data: formData,
        timeout:180000,
        processData: false,
        contentType: false,
        success:function(r){
        },
        error:function(r){  
        }
   });
}

Source code: Github address

Summarize

The above is the html+css+js that I introduced to you to realize the photo preview and upload picture function. I hope it will be helpful to you. If you have any questions, please leave me a message and I will reply to you in time. I would also like to thank everyone for their support of the 123WORDPRESS.COM website!

<<:  Solve the problem of specifying udp port number in docker

>>:  Detailed analysis of several situations in which MySQL indexes fail

Recommend

jQuery implements breathing carousel

This article shares the specific code of jQuery t...

How to install common components (mysql, redis) in Docker

Docker installs mysql docker search mysql Search ...

A collection of possible problems when migrating sqlite3 to mysql

Brief description Suitable for readers: Mobile de...

Building command line applications with JavaScript

Table of contents 1. Install node 2. Install Comm...

A great collection of web standards learning resources

These specifications are designed to allow for bac...

MySQL 8.0.12 winx64 detailed installation tutorial

This article shares the installation tutorial of ...

Example code for implementing anti-shake in Vue

Anti-shake: Prevent repeated clicks from triggeri...

Teach you step by step to develop a brick-breaking game with vue3

Preface I wrote a few examples using vue3, and I ...

MyBatis dynamic SQL comprehensive explanation

Table of contents Preface Dynamic SQL 1. Take a l...

Using Vue3 (Part 1) Creating a Vue CLI Project

Table of contents 1. Official Documentation 2. Cr...

MySQL stored procedure method example of returning multiple values

This article uses an example to describe how to r...

MySQL Community Server compressed package installation and configuration method

Today, because I wanted to install MySQL, I went ...

Web Design Tips: Simple Rules for Page Layout

Repetition: Repeat certain page design styles thr...

Detailed explanation of soft links and hard links in Linux

Table of contents 1. Basic storage of files and d...