zoukankan      html  css  js  c++  java
  • jquery 上传图片转为base64,ajax提交到后台

    支持多张图片上传、图片上传数量修改、可以删除
    
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width" />
        <title>jquery 图片base64</title>
        <script type="text/javascript" src="http://s28.9956.cn/static/v4/js/jquery-1.8.3.min.js"></script>
        <style type="text/css">
            *{margin: 0;padding: 0;}
            .popup-box {z-index:1010;}
            .img-div {border:1px solid #ddd;border-radius:100%;float:left;line-height:1;margin-left:5px;overflow:hidden;}
            /*上传图片插件的样式*/.fl {float:left;}
            .img-box .up-p {margin-bottom:20px;font-size:16px;color:#555;}
            .z_photo .z_file {position:relative;}
            .z_file  .file {100%;height:100%;opacity:0;position:absolute;top:0px;left:0px;z-index:100;}
            .z_photo .up-section {position:relative;margin-right:20px;border:1px solid #fff;}
            .up-section .close-upimg {position:absolute;top:6px;right:8px;display:none;z-index:10;}
            .up-section .up-span {display:block;100%;height:100%;visibility:hidden;position:absolute;top:0px;left:0px;z-index:9;}
            .up-section:hover {border:1px solid #1BBE60;}
            .up-section:hover .close-upimg {display:block;}
            .z_photo .up-img {display:block;100%;}
            .loading {border:1px solid #D1D1D1;background:url( https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1502943583253&di=196b6df604a7489dc247a217bf05c0b5&imgtype=0&src=http%3A%2F%2Fwww.xjsheying.com%2Fqqwebhimgs%2Fuploads%2Fbd565372.jpg) no-repeat center;}
            .up-opcity {opacity:0;}
            .img-name-p {display:none;}
            .upimg-div .up-section {140px;height:130px;overflow:hidden;}
            .img-box .upimg-div .z_file {140px;height:130px;overflow:hidden;}
            .z_file .add-img {display:block;140px;/* height:130px;*/}
            /*遮罩层样式*/.mask {z-index:1000;display:none;position:fixed;top:0px;left:0px;100%;height:100%;background:rgba(0,0,0,.4);}
            .mask .mask-content {500px;position:absolute;top:50%;left:50%;margin-left:-250px;margin-top:-80px;background:white;height:160px;text-align:center;}
            .mask .mask-content .del-p {color:#555;height:94px;line-height:94px;font-size:18px;border-bottom:1px solid #D1D1D1;}
            .mask-content .check-p {height:66px;line-height:66px;position:absolute;bottom:0px;left:0px;100%;}
            .mask-content .check-p span {49%;display:inline-block;text-align:center;color:#1BBE60;font-size:18px;}
            .check-p .del-com {border-right:1px solid #D1D1D1;}
        </style>
    </head>
    <body>
    <form enctype="multipart/form-data">
    <textarea id="testArea" style="display: block;  100%;height: 30px;"></textarea> 
    <div class="img-box full">
        <div class=" img-section">
            <div class="z_photo upimg-div clearfix" >
                <div class="z_file fl">
                    <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b10000_10000&sec=1502933359&di=adbb58e41f757cee3f62d2529d9ba5d6&src=http://pic.58pic.com/58pic/16/14/96/80T58PIC8Av_1024.jpg" class="add-img">
                    <input style=" 140px;height: 130px;" type="file" name="file" id="testFile" class="file" value="" accept="image/jpg,image/jpeg,image/png,image/bmp" multiple="multiple" />
                </div>
             </div>
         </div>
    </div>
    <div class="mask works-mask">
        <div class="mask-content">
            <p class="del-p ">您确定要删除图片吗?</p>
            <p class="check-p"><span class="del-com wsdel-ok" style="49%;margin-right: 0;margin-top: 0;">确定</span><span class="wsdel-no" style="49%;margin-right: 0;margin-top: 0;">取消</span></p>
        </div>
    </div>
    <button type="button" class="submit submitjc" style="margin-left: 0;">提交</button>
    </form>
    <script type="text/javascript">
        $("#testFile").change(function () {  
            run(this);  
        }); 
    	$(".submitjc").click(function(){
    
            var data_arr = {};
            data_arr.prid = {$detail['pr_id']};
            data_arr.prName = '{$detail['pr_name']}';
            data_arr.comName = '{$detail['companyInfo']['companyName']}';
        data_arr.comId = {$detail['com_id']};
    		data_arr.type = $("#type").val();
    		data_arr.code = {$detail['pr_code']};
    		data_arr.content  = $("#jccontent").val();
    		data_arr.file  = $("#testArea").val();
    		//data_arr.file  = $("#file")[0].file;
    
            $.ajax({
                type: 'Post',
                url: '/chanpin/{$detail['pr_id']}/correction/',
                data: data_arr,            
                async: false,  
                success: function (result) {  
                	alert("提交成功");
                 	$(".popup-box").hide();
                 	$("#jccontent,#file,#testArea").val("");
                 	$(".up-section").remove();
                 	$(".z_file").show();
                 	
                    if (result.Code == 200) {  
                        alert(result.Data);  
                    } else {  
                    }  
                }  
                
            });
    	});
    	function run(input_file) {  
            /*input_file:文件按钮对象*/  
            /*get_data: 转换成功后执行的方法*/  
            if (typeof (FileReader) === 'undefined') {  
                alert("抱歉,你的浏览器不支持 FileReader,不能将图片转换为Base64,请使用现代浏览器操作!");  
            } else {  
                try {  
                    /*图片转Base64 核心代码*/  
                    var file = input_file.files;  
    	            for(var i= 0;i<file.length;i++) {
    					//这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件  
    	                if (!/image/w+/.test(file[i].type)) {  
    	                    alert("请确保文件为图像类型");  
    	                    return false;  
    	                }  
    	                var reader = new FileReader();  
    	                reader.onload = function () {  
    	                	if(flag){
    	                		var currVal = $('#testArea').val();
    		                	if(!(currVal.length===0 || currVal ==null)) currVal+='#';
    		                	$('#testArea').val(currVal+this.result);
    	                	}
    	                }  
    	                reader.readAsDataURL(file[i]);  
                   }
                } catch (e) {  
                    alert('图片转Base64出错啦!' + e.toString())  
                }  
            }  
        }
    // <!-- 上传图片 -->
    var flag = true;
    $(function(){
        var delParent;
        var defaults = {
            fileType         : ["jpg","png","bmp","jpeg","gif"],   // 上传文件的类型
            fileSize         : 1024 * 1024 * 2                  // 上传文件的大小 10M
        };
            /*点击图片的文本框*/
        $(".file").change(function(){    
        	flag = true;
            var idFile = $(this).attr("id");
            var file = document.getElementById(idFile);
            var imgContainer = $(this).parents(".z_photo"); //存放图片的父亲元素
            var fileList = file.files; //获取的图片文件
            var input = $(this).parent();//文本框的父亲元素
            var imgArr = [];
            //遍历得到的图片文件
            var numUp = imgContainer.find(".up-section").length;
            var totalNum = numUp + fileList.length;  //总的数量
            if(fileList.length > 3 || totalNum > 3 ){
            	flag = false;
                alert("上传图片数目不可以超过3个,请重新选择");  //一次选择上传超过3个 或者是已经上传和这次上传的到的总数也不可以超过3个
    
            }
            else if(numUp < 3){
                fileList = validateUp(fileList);
                for(var i = 0;i<fileList.length;i++){
                 var imgUrl = window.URL.createObjectURL(fileList[i]);
                     imgArr.push(imgUrl);
                 var $section = $("<section class='up-section fl loading'>");
                     imgContainer.append($section);
                 var $span = $("<span class='up-span'>");
                     $span.appendTo($section);
                
                 var $img0 = $("<img class='close-upimg'>").on("click",function(event){
                        event.preventDefault();
                        event.stopPropagation();
                        $(".works-mask").show();
                        delParent = $(this).parent();
                    });   
                    $img0.attr("src","{$resDomainPath}/product/images/a7.png").appendTo($section);
                 var $img = $("<img class='up-img up-opcity'>");
                     $img.attr("src",imgArr[i]);
                     $img.appendTo($section);
                 var $p = $("<p class='img-name-p'>");
                     $p.html(fileList[i].name).appendTo($section);
                 var $input = $("<input id='taglocation' name='taglocation' value='' type='hidden'>");
                     $input.appendTo($section);
                 var $input2 = $("<input id='tags' name='tags' value='' type='hidden'/>");
                     $input2.appendTo($section);
                  
               }
            }
            setTimeout(function(){
                 $(".up-section").removeClass("loading");
                 $(".up-img").removeClass("up-opcity");
             },450);
             numUp = imgContainer.find(".up-section").length;
            if(numUp >= 3){
                $(this).parent().hide();
            }
        });
        
        
       
        $(".z_photo").delegate(".close-upimg","click",function(){
              $(".works-mask").show();
              delParent = $(this).parent();
        });
            
        $(".wsdel-ok").click(function(){
            $(".works-mask").hide();
            var numUp = delParent.siblings().length;
            if(numUp < 4){
                delParent.parent().find(".z_file").show();
            }
            delParent.remove();
    
            // delParent  删除图片的base64
            var selImg = $(".up-section"),
            	selImgValue = $('#testArea').val().split('#'),
            	delIndex = 0;
            for(var i = 0;i<selImg.length;i++) {
            	if(selImg[i] === delParent[0]) {
    				delIndex = i;break;
            	}
            }
            selImgValue.splice(delIndex, 1);
            $('#testArea').val(selImgValue.join('#'));
        });
        
        $(".wsdel-no").click(function(){
            $(".works-mask").hide();
        });
            
            function validateUp(files){
                var arrFiles = [];//替换的文件数组
                for(var i = 0, file; file = files[i]; i++){
                    //获取文件上传的后缀名
                    var newStr = file.name.split("").reverse().join("");
                    if(newStr.split(".")[0] != null){
                            var type = newStr.split(".")[0].split("").reverse().join("");
                            console.log(type+"===type===");
                            if(jQuery.inArray(type, defaults.fileType) > -1){
                                // 类型符合,可以上传
                                if (file.size >= defaults.fileSize) {
                                    alert(file.size);
                                    alert('您这个"'+ file.name +'"文件大小过大');    
                                } else {
                                    // 在这里需要判断当前所有文件中
                                    arrFiles.push(file);    
                                }
                            }else{
                                alert('您这个"'+ file.name +'"上传类型不符合');   
                            }
                        }else{
                            alert('您这个"'+ file.name +'"没有类型, 无法识别');    
                        }
                }
                return arrFiles;
            }
    })
    </script>
    
    </body>
    </html>
      
    

      

  • 相关阅读:
    poj 2187 Beauty Contest(旋转卡壳)
    poj 2540 Hotter Colder(极角计算半平面交)
    poj 1279 Art Gallery(利用极角计算半平面交)
    poj 3384 Feng Shui(半平面交的联机算法)
    poj 1151 Atlantis(矩形面积并)
    zoj 1659 Mobile Phone Coverage(矩形面积并)
    uva 10213 How Many Pieces of Land (欧拉公式计算多面体)
    uva 190 Circle Through Three Points(三点求外心)
    zoj 1280 Intersecting Lines(两直线交点)
    poj 1041 John's trip(欧拉回路)
  • 原文地址:https://www.cnblogs.com/wangjae/p/7380021.html
Copyright © 2011-2022 走看看