黯厢
黯厢
  • 发布:2020-05-08 11:15
  • 更新:2020-05-08 11:15
  • 阅读:2294

HTML5+表单新增、删除、预览、上传图片

分类:MUI
第一种方法:表单提交,使用jquery的Ajax  
<!DOCTYPE html>  
<html>  
    <head>  
        <meta charset="utf-8">    
        <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover" />  
        <meta name="apple-mobile-web-app-capable" content="yes" />  
        <meta name="apple-mobile-web-app-status-bar-style" content="black" />  
    </head>  
    <body>  
        <style>  
            .preview ul {  
                margin: 0;  
                padding: 0;  
            }  
            .preview ul li {  
                position: relative;  
                display: inline-block;  
                margin-top: 10px;  
                margin-bottom: 10px;  
                margin-right: 10px;  
                float: left;  
                list-style: none;  
            }  
            .preview ul li img {  
                width: 50px;  
                height: 50px;  
                border-radius: 5px;  
            }  
            .preview ul li input {  
                display: inline-block;  
                position: absolute;  
                width: 50px;  
                height: 50px;  
                left: 0;  
                top: 0;  
                opacity: 0;  
            }  
            .del {  
                display: inline-block;  
                position: absolute;  
                top:6px;  
                right: 0px;  
                width: 12px;  
                height: 2px;  
                background: #ED544D;  
                line-height: 0;  
                font-size: 0;  
                vertical-align: middle;  
                -webkit-transform: rotate(45deg);  
            }  
            .del:after {  
                content: "/";  
                display: block;  
                width: 12px;  
                height: 2px;  
                background: #ED544D;  
                -webkit-transform: rotate(-90deg);  
            }  
        </style>  
    <header class="mui-bar mui-bar-nav" >  
        <a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>  
        <div class="mui-title">图片预览上传</div>  
    </header>  
    <div class="mui-content" >  
        <form id='from1' enctype = "multipart/form-data">  
            <div style="margin-top: 16px;margin-bottom: 10px;">  
                <span class="title">添加照片(选填)</span>  
                <span id="picnum" style="float: right;margin-right: 20px;font-size: 12px; color: #666666;">0/4</span>  
            </div>  
            <div class="preview" style="background-color: #ffffff;height: 70px;width: 100%;padding-left: 15px;padding-right: 15px;">  
                <ul class="row mui-input-row">  
                    <li>  
                        <input id="file"  type="file" name="upload" accept="image/*"  
                               onchange="setImagePreviews();"  multiple="true" />  
                        <img src="../images/adddd.png"/>  
                    </li>  
                </ul>  
            </div>  
            <div style="margin-top: 16px;width: 100%;text-align: center;">  
                <button style="background-color: #169BD5;height: 40px;width: 266px;font-size: 14px;color: #FFFFFF;border-radius: 5px;border: 0px;" type="button" onclick="trans()">提交</button>  
            </div>  
        </form>  
    </div>  

    </body>  
<script src="../js/mui.min.js"></script>  
<script src="../js/jquery.min.js"></script>  
<script type="text/javascript">  
    mui.init({  
        swipeBack:true //启用右滑关闭功能  
        });  
    function submit(){  
        var formData = new FormData();  
        formData.append('name',name);  
        if(uploadfile.length>0){  
            for(var i=0;i<uploadfile.length;i++){  
                formData.append("upload", uploadfile[i]); // 文件对象  
            }  
        }  
        var url= ;  
        jQuery.ajax({  
          url: url,  
          type: 'post',  
          async: false,  
          contentType:false,  
          processData: false,  
          data:formData,  
          xhrFields: {  
            withCredentials: true  
          },  
          crossDomain: true,  
          success: function (data) {  
            console.log(JSON.stringify(data));  
            mui.toast("提交成功!",{ duration:'500', type:'div' });  
          },  
          error: function (error) {  
            console.log(JSON.stringify(error));  
            mui.toast('页面出错',{ duration:'500', type:'div' });  
          }  
        });  
    }  
    var uploadfile = [];  
    function setImagePreviews() {  
        var docObj = document.getElementById("file");  
        var piclength = uploadfile.length;  
        var fileList = docObj.files;  
        if((Number(piclength) + Number(fileList.length)) > 4) {  
            plus.nativeUI.alert('最多上传四张');  
        } else {  
            document.getElementById("picnum").innerText=Number(piclength) + Number(fileList.length)+'/4';  
            for(var i = 0; i < fileList.length; i++) {  
                uploadfile.push(docObj.files[i]);  
                var picid = Number(piclength) + Number(i);  
                var reader = new FileReader();  
                reader.readAsDataURL(docObj.files[i]);                      
                reader.onload = function(e) {  
                // 图片base64化  
                var newUrl = this.result;  
                $(".preview ul").prepend("<li onclick='delImg(this)'><img src='" + newUrl + "' /><span class='del'></span></li>");  
                };  

            }  
        }  
    }  
    function delImg(obj){  
        var list =document.getElementsByTagName('li');  
        for(var i=0;i<list.length;i++){  
            list[i].index=i;  
        }  
        var idx=2-obj.index;  
        var ul=obj.parentNode;  
        var btnArray=['是','否'];  
        plus.nativeUI.confirm("确定要删除此图?",function(e){  
            if(e.index==0){  
                ul.removeChild(obj);  
                uploadfile.splice(idx,1);  
                document.getElementById("picnum").innerText=Number(uploadfile.length)+'/4';  
            }  
        },{"buttons":btnArray})  
    }  
</script>  
</html>  
第二种:使用plus.uploader  

<!DOCTYPE html>  
<html>  
    <head>  
        <meta charset="utf-8">    
        <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover" />  
        <meta name="apple-mobile-web-app-capable" content="yes" />  
        <meta name="apple-mobile-web-app-status-bar-style" content="black" />  
    </head>  
    <body>  
        <style>  
            .dynamic_images ul {  
                margin: 0;  
                padding: 0;  
            }  
            .dynamic_images ul li {  
                position: relative;  
                display: inline-block;  
                margin-top: 10px;  
                margin-bottom: 10px;  
                margin-right: 10px;  
                float: left;  
                list-style: none;  
            }  
            .dynamic_images ul li img {  
                width: 50px;  
                height: 50px;  
                border-radius: 5px;  
            }  
            .del {  
                display: inline-block;  
                position: absolute;  
                top:6px;  
                right: 0px;  
                width: 12px;  
                height: 2px;  
                background: #ED544D;  
                line-height: 0;  
                font-size: 0;  
                vertical-align: middle;  
                -webkit-transform: rotate(45deg);  
            }  
            .del:after {  
                content: "/";  
                display: block;  
                width: 12px;  
                height: 2px;  
                background: #ED544D;  
                -webkit-transform: rotate(-90deg);  
            }  
        </style>  
    <header class="mui-bar mui-bar-nav" >  
        <a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>  
        <div class="mui-title">图片预览上传</div>  
    </header>  
    <div class="mui-content" >  
        <form id='from1' enctype = "multipart/form-data">  
            <div style="margin-top: 16px;margin-bottom: 10px;">  
                <span class="title">添加照片(选填)</span>  
                <span id="picnum" style="float: right;margin-right: 20px;font-size: 12px; color: #666666;">0/4</span>  
            </div>  
            <div class="dynamic_images" style="background-color: #ffffff;height: 70px;width: 100%;padding-left: 15px;padding-right: 15px;">  
                <ul class="row mui-input-row">  
                    <li>  
                        <img src="../images/adddd.png" id="addnew" onclick="showActionSheet();" />  
                    </li>  
                </ul>  
            </div>  
            <div style="margin-top: 16px;width: 100%;text-align: center;">  
                <button style="background-color: #169BD5;height: 40px;width: 266px;font-size: 14px;color: #FFFFFF;border-radius: 5px;border: 0px;" type="button" onclick="submit()">提交</button>  
            </div>  
        </form>  
    </div>  
    </body>  
<script src="../js/mui.min.js"></script>  
<script src="../js/jquery.min.js"></script>  
<script type="text/javascript">  
    mui.init({  
        swipeBack:true //启用右滑关闭功能  
        });  

    function submit(){  
        var url= ;  
        var task = plus.uploader.createUpload( url,   
            { method:"POST",blocksize:204800,priority:100 },  
            function ( t, status ) {  
                // 上传完成  
                if ( status == 200 ) {   
                    wt.close();  
                    console.log( "Upload success: " + JSON.stringify(t));  
                } else {  
                    wt.close();  
                    console.log( "Upload failed: " + JSON.stringify(status));  
                }  
            });  
            for(var i = 0; i < files.length; i++) {    
                var f = files[i];    
                task.addFile(f.path,{  
                    key: f.name,  
                    name:'upload',  
                });  
            }  
            task.addData('name',name);  
            task.start();  
    }  

    var files = [];  
    // 添加文件  
    var index = 1;  
    var newUrlAfterCompress;  
    function appendFile(p) {  
        files.push({  
            name: "uploadkey" + index,//这个值服务器会用到,作为file的key  
            path: p  
        });  
        index++;  
    }  
    function showActionSheet() {  
        if($(".dynamic_images ul li").length<5){  
            var bts = [{  
                title: "拍照"  
            }, {  
                title: "从相册选择"  
            }];  
            plus.nativeUI.actionSheet({  
                    cancel: "取消",  
                    buttons: bts  
                },  
            function(e) {  
                    if (e.index == 1) {  
                        getImage();  
                    } else if (e.index == 2) {  
                        galleryImgs();  
                    }  
                }  
            );  
        }else{  
            plus.nativeUI.alert('最多上传四张图片!');  
        }  
    }  
    // 产生一个随机数  
    function getUid() {  
        return Math.floor(Math.random() * 100000000 + 10000000).toString();  
    }  
    //拍照  
    function getImage() {  
        var cmr = plus.camera.getCamera();  
        cmr.captureImage(function(p) {  
            plus.io.resolveLocalFileSystemURL(p, function(entry) {  
                var localurl = entry.toLocalURL(); //  
                $(".dynamic_images ul").prepend("<li onclick='delImg(this)'><img src='" + localurl + "' /><span class='del'></span></li>");  
                var dstname="_downloads/"+getUid()+".png";//设置压缩后图片的路径  
                newUrlAfterCompress=compressImage(localurl,dstname);  
                appendFile(dstname);  
                document.getElementById("picnum").innerText=files.length+'/4';  
            });  
        });  
    }  
    function galleryImgs() {  
        // 从相册中选择图片  
        var num=4;  
        if(5-$(".dynamic_images ul li").length>=1){  
            num=5-$(".dynamic_images ul li").length;  
        }  
        plus.gallery.pick(function(e) {  
            for (var i = 0; i < e.files.length; i++) {  
                $(".dynamic_images ul").prepend(  
                    "<li  onclick='delImg(this)'><img  src='" + e.files[i] + "'/><span class='del'></span></li>");  
                    var dstname="_downloads/"+getUid()+".png";//设置压缩后图片的路径  
                    newUrlAfterCompress=compressImage(e.files[i],dstname);  
                    appendFile(dstname);  
            }  
            document.getElementById("picnum").innerText=files.length+'/4';  
        }, function(e) {   
            console.log("取消选择图片");  
        }, {  
            filter: "image",  
            multiple: true,  
            maximum:num,  
            system:false,  
            onmaxed:function(){  
                plus.nativeUI.alert('最多只能选择四张图片');  
            }  
        });  
    }  
    //压缩图片,这个比较变态的方法,无法return  
    function compressImage(src,dstname) {  
        //兼容  
        if (0 != src.toString().indexOf("file://")) {  
            src = "file://" + src;  
        }  
        plus.zip.compressImage({  
                src: src,  
                dst: dstname,  
                overwrite:true,  
                quality: 5  
            },  
            function(event) {  
                //console.log("Compress success:"+event.target);  
                return event.target;  
            },  
            function(error) {  
                console.log(error);  
                return src;  
            });  

    }  
     function delImg(obj)  
     {  
        var list =document.getElementsByTagName('li');  
        for(var i=0;i<list.length;i++){  
            list[i].index=i;  
        }  
        var idx=2-obj.index;  
        var ul=obj.parentNode;  
        var btnArray=['是','否'];  
        plus.nativeUI.confirm("确定要删除此图?",function(e){  
            if(e.index==0){  
                ul.removeChild(obj);  
                files.splice(idx,1);  
                document.getElementById("picnum").innerText=Number(files.length)+'/4';  
            }  
        },{"buttons":btnArray})  
     }  
</script>  
</html>  
0 关注 分享

要回复文章请先登录注册