, although this method can also achieve the function, the user experience may be compromised. It's a bit different, so this article records the use of css+js to implement the preview and compressed upload functions after the image is selected. Some of the information comes from the Internet, and is recorded and organized here."/> , although this method can also achieve the function, the user experience may be compromised. It's a bit different, so this article records the use of css+js to implement the preview and compressed upload functions after the image is selected. Some of the information comes from the Internet, and is recorded and organized here.">
search
HomeWeb Front-endCSS Tutorialhtml+css+js implements photo preview and upload image function example sharing

When we make web pages, we often need to upload pictures. We may choose pictures or take photos to upload. If we simply use

<input type="file"/>

, although this method can also achieve the function, it may be difficult in terms of user experience. It will be a little different, so this article records the use of css+js to implement the preview and compressed upload functions after the image is selected. Some of them come from the Internet, and are recorded and organized 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>拍照上传</title>
        <link rel="stylesheet" href="index.css"/>
        <script type=&#39;text/javascript&#39; src=&#39;index.js&#39; charset=&#39;utf-8&#39;></script>
    </head>
    <body>
         <form id="mainForm">
            <p class="content">
                <p class="label">身份证</p>
                <p class="img-area">
                    <p class="container">
                        <input type="file" id=&#39;id-face&#39; name=&#39;face&#39;  accept="image/*" />
                        <p id=&#39;face-empty-result&#39;>
                            <img src="/static/imghwm/default1.png"  data-src="https://github.com/wangheng3751/my-resources/blob/master/images/camera.png?raw=true"  class="lazy"  style=&#39;width:4rem&#39;  alt="">
                            <p>身份证正面照</p>
                        </p>
                        <img  style=&#39;width: 100%&#39; id=&#39;face-result&#39;/ alt="html+css+js implements photo preview and upload image function example sharing" >
                    </p>
                    <p class="container" style=&#39;margin-top:0.5rem;&#39;>
                        <input type="file" id=&#39;id-back&#39; name=&#39;back&#39; accept="image/*" />
                        <p id=&#39;back-empty-result&#39;>
                            <img src="/static/imghwm/default1.png"  data-src="https://github.com/wangheng3751/my-resources/blob/master/images/camera.png?raw=true"  class="lazy"  style=&#39;width:4rem&#39;  alt="">
                            <p>身份证反面照</p>
                        </p>
                        <img  style=&#39;width: 100%&#39; id=&#39;back-result&#39;/ alt="html+css+js implements photo preview and upload image function example sharing" >
                    </p>
                </p>
            </p>
            <p class="btn">
                提交
            </p>
         </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 p{
    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();
    });
};
/**
 * 选中图片时的处理
 * @param {*} fileObj input file元素
 * @param {*} el //选中后用于显示图片的元素ID
 * @param {*} btnel //未选中图片时显示的按钮区域ID
 */
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;
    }
}
/**
 * 将图片压缩后返回base64格式的数据
 * @param {*} image img元素
 * @param {*} width 压缩后图片宽度
 * @param {*} height 压缩后图片高度
 * @param {*} qua //图片质量1-100
 */
function compressImageTobase64(image,width,height,qua){
    var quality = qua ? qua / 100 : 0.8;
    var canvas = document.createElement("canvas"),     
        ctx = canvas.getContext(&#39;2d&#39;);     
    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;
}
//提交
function submit(){
    //1、form提交
    //document.getElementById("mainForm").submit();
    //2、压缩后ajax提交
    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);
    //需引入jQuery
    $.ajax({
        url:"/地址",
        type: &#39;POST&#39;,
        cache: false,
        data: formData,
        timeout:180000,
        processData: false,
        contentType: false,
        success:function(r){
        },
        error:function(r){  
        }
   });
}

Related recommendations:

Using JavaScript to preview and upload images without refreshing the page tutorial

javascript Solutions to problems found when previewing uploaded images_Image special effects

jQuery implements local preview of uploaded images_jquery

The above is the detailed content of html+css+js implements photo preview and upload image function example sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
A Little Reminder That Pseudo Elements are Children, Kinda.A Little Reminder That Pseudo Elements are Children, Kinda.Apr 19, 2025 am 11:39 AM

Here's a container with some child elements:

Menus with 'Dynamic Hit Areas'Menus with 'Dynamic Hit Areas'Apr 19, 2025 am 11:37 AM

Flyout menus! The second you need to implement a menu that uses a hover event to display more menu items, you're in tricky territory. For one, they should

Improving Video Accessibility with WebVTTImproving Video Accessibility with WebVTTApr 19, 2025 am 11:27 AM

"The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect."- Tim Berners-Lee

Weekly Platform News: CSS ::marker pseudo-element, pre-rendering web components, adding Webmention to your siteWeekly Platform News: CSS ::marker pseudo-element, pre-rendering web components, adding Webmention to your siteApr 19, 2025 am 11:25 AM

In this week's roundup: datepickers are giving keyboard users headaches, a new web component compiler that helps fight FOUC, we finally get our hands on styling list item markers, and four steps to getting webmentions on your site.

Making width and flexible items play nice togetherMaking width and flexible items play nice togetherApr 19, 2025 am 11:23 AM

The short answer: flex-shrink and flex-basis are probably what you’re lookin’ for.

Position Sticky and Table HeadersPosition Sticky and Table HeadersApr 19, 2025 am 11:21 AM

You can't position: sticky; a

Weekly Platform News: HTML Inspection in Search Console, Global Scope of Scripts, Babel env Adds defaults QueryWeekly Platform News: HTML Inspection in Search Console, Global Scope of Scripts, Babel env Adds defaults QueryApr 19, 2025 am 11:18 AM

In this week's look around the world of web platform news, Google Search Console makes it easier to view crawled markup, we learn that custom properties

IndieWeb and WebmentionsIndieWeb and WebmentionsApr 19, 2025 am 11:16 AM

The IndieWeb is a thing! They've got a conference coming up and everything. The New Yorker is even writing about it:

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.