weui多张图片上传前端+后台

一开始搞这个玩意我用原生的html来写是真的丑,最后网上找了很多但是没什么完整的,所以自己写了个完整的,大神轻喷

前端代码用的是weUI封装好的样式(这里我加了最多三张的限制),可以调动相机

<div class="weui-gallery" id="gallery">  
            <span class="weui-gallery__img" id="galleryImg"></span>  
            <div class="weui-gallery__opr">  
                <a href="javascript:" class="weui-gallery__del">  
                    <i class="weui-icon-delete weui-icon_gallery-delete" style="margin-bottom: 50px"></i>  
                </a>  
            </div>  
        </div>  
	<div class="weui-cells weui-cells_form">  
            <div class="weui-cell">  
                <div class="weui-cell__bd">  
                    <div class="weui-uploader">  
                        <div class="weui-uploader__hd">  
                            <p class="weui-uploader__title">图片上传(最多三张):</p>  
                        </div>  
                        <div class="weui-uploader__bd">  
                            <ul class="weui-uploader__files" id="uploaderFiles">  
                                  
                            </ul>  
                            <div class="weui-uploader__input-box">  
                                <input id="uploaderInput" class="weui-uploader__input zjxfjs_file" type="file" accept="image/*" multiple="" capture="camera">  
                            </div>  
                        </div>  
                    </div>  
                </div>  
            </div>  
        </div>  

js代码 基本还是weui的代码,里面添加了一些限制和修改了一部分;这个地方根据网友的修改,更改fileArr.splice(index,index)为

fileArr.splice(index,1);

$(function() {  
	        var tmpl = '<li class="weui-uploader__file" style="background-image:url(#url#)"></li>',  
	            $gallery = $("#gallery"),  
	            $galleryImg = $("#galleryImg"),  
	            $uploaderInput = $("#uploaderInput"),  
	            $uploaderFiles = $("#uploaderFiles");  
            $uploaderInput.on("change", function(e) {  
                var src, url = window.URL || window.webkitURL || window.mozURL,  
                files = e.target.files;
                var length=fileArr.length;
                for(var i = 0, len = files.length; i < len; ++i) {  
                    var file = files[i];
                    if(length + i + 1 > 3) {
                        break;
                    }  
  					fileArr.push(file);
                    if(url) {  
                        src = url.createObjectURL(file);  
                    } else {  
                        src = e.target.result;  
                    }  
                    $uploaderFiles.append($(tmpl.replace('#url#', src)));  
                }  
                checkPhotoSize();
            }); 
            
	        //控制显示三张以内照片
	        function checkPhotoSize(){
                if(fileArr.length>2){
                	$(".weui-uploader__input-box").hide();
                }else{
                	$(".weui-uploader__input-box").show();
                }
	        }
	             
	        var index; //第几张图片  
	        $uploaderFiles.on("click", "li", function() {  
	            index = $(this).index();  
	            $galleryImg.attr("style", this.getAttribute("style"));  
	            $gallery.fadeIn(100);  
	        });  
	        $gallery.on("click", function() {  
	            $gallery.fadeOut(100);  
	        });  
	        //删除图片  
	        $(".weui-gallery__del").click(function() {  
	            $uploaderFiles.find("li").eq(index).remove();
	            fileArr.splice(index,1);
	            checkPhotoSize();  
	        });

js提交文件到后台

var fileArr=new Array();这里需要一个全局变量来接受文件

if(fileArr.length!=0){
			          		var formData = new FormData();
			          		for(var i = 0;i<fileArr.length;i++){
			          			formData.append("file[]",fileArr[i]);
			          		}
			        		$.ajax({
								    url: "../../xxx/xxx.do",
								    type: "POST",  
								    async: false,  
								    cache: false, 
								    processData: false,// 告诉jQuery不要去处理发送的数据
								    contentType: false,// 告诉jQuery不要去设置Content-Type请求头
								    data: formData,
								    success: function(data){
								    }
								});
						}
			          	$.toast("保存成功", 5000);
			          	window.location.href = "xxxx.html";
		          	}else{
		          		$.toast("未知错误,请于管理员联系", 2000);
		          	}

java后台接收代码 (这个后台代码也是从网上找的,但是网上代码有很多问题,根据实际来改)

        @ResponseBody
	@RequestMapping("/xxxx.do")
	public String uploadPictureList( HttpServletRequest request) throws Exception{
	    MultipartHttpServletRequest muRequest =(MultipartHttpServletRequest) request;
		List<MultipartFile> files = muRequest.getFiles("file[]");
		
            File targetFile=null;
	    String msg="";//返回存储路径
	    int code=1;
	    List imgList=new ArrayList();
	    /*if (files!=null && files.length>0) {
	        for (int i = 0; i < files.length; i++) {*/
	    if (files!=null && files.size()>0) {
	        for (int i = 0; i < files.size(); i++) {
	            //String fileName=files[i].getOriginalFilename();//获取文件名加后缀
	        	String fileName=files.get(i).getOriginalFilename();//获取文件名加后缀
	            if(fileName!=null&&fileName!=""){   
	                String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/upload/imgs/";//存储路径
	                String path = request.getSession().getServletContext().getRealPath("upload/imgs"); //文件存储位置
	                String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
	                fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;//新的文件名

	                //先判断文件是否存在
	                String fileAdd = DateUtil.formatDate(new Date(),"yyyyMMdd");
	                File file1 =new File(path+"//"+fileAdd); 
	                //如果文件夹不存在则创建    
	                if(!file1 .exists()  && !file1 .isDirectory()){       
	                    file1 .mkdirs();  
	                }
	                targetFile = new File(file1, fileName);
	                //targetFile = new File(path);
	                //System.out.println(targetFile+"xc");
	                try {
	                   // files[i].transferTo(targetFile);
	                    files.get(i).transferTo(targetFile);
	                    msg=returnUrl+fileAdd+"/"+fileName;
	                    imgList.add(msg);
	                } catch (Exception e) {
	                    e.printStackTrace();
	                }
	                
	            }
	        }
	    } 
	    
	    return JSONArray.fromObject(imgList).toString();
	}

 

如有不当之处请各位指教,如有疑问可加QQ:201239785或2228037791

如有bug大家在评论下面可以提出

 

发布了3 篇原创文章 · 获赞 5 · 访问量 6844
展开阅读全文

微信公众号拍照上传多张图片接口

03-03

# 现在可以往数据库存储多张照片,但是调用不了拍照接口 ``` <div class="container"> <div class="weui_cells weui_cells_form"> <div class="weui_cell"> <div class="weui_cell_bd weui_cell_primary"> <div class="weui_uploader"> <div class="weui_uploader_hd weui_cell"> <img alt="img" src="/szgmjk/image/icon5.png">   <div class="weui_cell_bd weui_cell_primary">现场拍照</div> <div class="weui_cell_ft js_counter">0/6</div> </div> <div class="weui_uploader_bd"> <ul class="weui_uploader_files js_previews"> <!-- 预览图插入到这 --> </ul> <div class="weui_uploader_input_wrp"> <input class="weui_uploader_input js_file" type="file" accept="image/jpg,image/jpeg,image/png,image/gif" multiple=""> </div> </div> </div> </div> </div> </div> </div> <div class="preview"> <div class="weui_mask"></div> <img src="" alt="" /> <a href="javascript:;" class="delete" id="delete">delete</a> </div> //拍照上传接口 // codepen 没办法直接在 body 标签加属性,所以用这里用 js 给 body 添加 ontouchstart 属性来触发 :active document.body.setAttribute('ontouchstart', ''); $(function () { // 允许上传的图片类型 var allowTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif']; //10MB var maxSize = 10 * 1024 * 1024; // 图片最大宽度 var maxWidth = 300; // 最大上传图片数量 var maxCount = 6; var images = []; $('.js_file').on('change', function (event) { var files = event.target.files; // 如果没有选中文件,直接返回 if (files.length === 0) { return; } for (var i = 0, len = files.length; i < len; i++) { var file = files[i]; var reader = new FileReader(); // 如果类型不在允许的类型范围内 if (allowTypes.indexOf(file.type) === -1) { $.weui.alert('该类型不允许上传'); continue; } if (file.size > maxSize) { $.weui.alert('图片太大,不允许上传'); continue; } if ($('.weui_uploader_file').length >= maxCount) { $.weui.alert('最多只能上传' + maxCount + '张图片'); return; } reader.onload = function (e) { var img = new Image(); img.onload = function () { // 不要超出最大宽度 var w = Math.min(maxWidth, img.width); // 高度按比例计算 var h = img.height * (w / img.width); var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); // 设置 canvas 的宽度和高度 canvas.width = w; canvas.height = h; ctx.drawImage(img, 0, 0, w, h); var base64 = canvas.toDataURL('image/png'); var base65 = canvas.toDataURL('image/png'); var base66 = canvas.toDataURL('image/png'); var base67 = canvas.toDataURL('image/png'); var base68 = canvas.toDataURL('image/png'); var base69 = canvas.toDataURL('image/png'); document.getElementById("picture").value = base64; document.getElementById("picture2").value = base65; document.getElementById("picture3").value = base66; document.getElementById("picture4").value = base67; document.getElementById("picture5").value = base68; document.getElementById("picture6").value = base69; // 插入到预览区 var $preview = $('<li class="weui_uploader_file weui_uploader_status" style="background-image:url(' + base64 + ')"><div class="weui_uploader_status_content">0%</div></li>'); $('.weui_uploader_files').append($preview); var num = $('.weui_uploader_file').length; $('.js_counter').text(num + '/' + maxCount); images.push(base64); // 然后假装在上传,可以post base64格式,也可以构造blob对象上传 var progress = 0; function uploading() { $preview.find('.weui_uploader_status_content').text(++progress + '%'); if (progress < 100) { setTimeout(uploading, 30); } else { // 如果是失败,塞一个失败图标 //$preview.find('.weui_uploader_status_content').html('<i class="weui_icon_warn"></i>'); $preview.removeClass('weui_uploader_status').find('.weui_uploader_status_content').remove(); } } setTimeout(uploading, 30); }; img.src = e.target.result; }; reader.readAsDataURL(file); } }); $('.js_previews').on('click', '.weui_uploader_file', function(event){ var index = $(this).index(); var img = images[index]; $('.preview').find('img').attr('src', img); $('.preview').show(); }); }); $(function() { var msg = $("#msg").val(); if (msg != "" && msg.length > 0) { $.alert(msg); } var max = 200; $('#textarea').on( 'input', function() { var text = $(this).val(); var len = text.length; $('#count').text(len); if (len > max) { $(this).closest('.weui_cell').addClass( 'weui_cell_warn'); } else { $(this).closest('.weui_cell').removeClass( 'weui_cell_warn'); } }); }); ``` 求解决,怎么在上传多张图片代码中和拍照接口结合, 如有解决,请留下支付方式,另有重谢。 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览