h5 端图片上传-模拟多张上传
1、由于后端的限制,上传图片到服务器只能的一张一张传
2、显示图片预览是本地的图片
3、根据服务器返回的结果拿到相应的路径保存到提交评论的接口中
4、删除的时候,需要删除对应的路径,不要把删除的提交到评论的接口中
A、comment-detail.js
var status = common.getQueryStr("status"); var subsId = common.getQueryStr("subsId"); var isList = common.getQueryStr("isList"); var prodId = common.getQueryStr("prodId"); var CommentDetail = { point : 5, commentCon: '', uploadImg:[], everyUploadCount:0, layerLoadingIndex:null, submitComment : function (param) { var obj = param.obj; obj.click(function(){ var url = '/app/comment'; if(CommentDetail.commentCon.length<10){ alert("文字最少限制10字"); return; } if(CommentDetail.commentCon.length>500){ alert("文字最多限制500字"); return; } var imagesUrl = ''; for(var i=0;i<CommentDetail.uploadImg.length;i++){ if(i==CommentDetail.uploadImg.length-1){ imagesUrl += CommentDetail.uploadImg[i].savepath; }else{ imagesUrl += CommentDetail.uploadImg[i].savepath +','; } } var params = { "reqBody":{ "bossProdId" : prodId, "content" : CommentDetail.commentCon, "subsId" : subsId, "score" : CommentDetail.point, "images": imagesUrl } } common.ajax("POST",url,params,null,function (ret) { if(ret.resultCode==0){ alertDialog('提交成功',function () { $("#go-to-back").click(); }); } }); }); }, imgFileUpload : function () { var input = document.getElementById("imgFileUpload"); var result,div; if(typeof FileReader==='undefined'){ result.innerHTML = "抱歉,你的浏览器不支持 FileReader"; input.setAttribute('disabled','disabled'); }else{ input.addEventListener('change',readFile,false); } function readFile(){ var files = this.files; var liLength= $("#commentImgList li.li-img").length; var count = files.length>6-liLength ? 6-liLength : files.length; CommentDetail.everyUploadCount = count; CommentDetail.layerLoadingIndex = layer.open({ type: 2 ,content: '加载中' ,shadeClose:false }); for(var i=0;i<count;i++){ if (!input['value'].match(/.jpg|.gif|.png|.bmp/i)){ return alert("上传的图片格式不正确,请重新选择") } var item = files[i]; (function(img) { var mpImg = new MegaPixImage(img); var resImg = document.createElement("img"); var items = item; resImg.file = img; mpImg.render(resImg, { maxWidth: 1280, maxHeight: 960, quality: 1 }, function() { var wdh = Number(resImg.width)>Number(resImg.height)? true : false; var commentListLiHeight = Number((window.screen.width)*0.92*0.3).toFixed(1); if(wdh){ var htmlStr = '<li class="li-img"><a style="height: '+commentListLiHeight+'px" href="javascript:;"><img src="'+resImg.src+'" class="dataImg" onclick="CommentDetail.initSwiper(this)" style="width: 100%;"></a><i class="icon-del" onclick="CommentDetail.delImage(this,\''+items.name+'\')"></i></li>' }else{ var htmlStr = '<li class="li-img"><a style="height: '+commentListLiHeight+'px" href="javascript:;"><img src="'+resImg.src+'" class="dataImg" onclick="CommentDetail.initSwiper(this)" style="height: 100%;"></a><i class="icon-del" onclick="CommentDetail.delImage(this,\''+items.name+'\')"></i></li>' } $("#commentImgList").prepend(htmlStr); CommentDetail.uploadShowHide(); CommentDetail.fileUpload(resImg.src, item.type,items.name); }); })(item); } } }, fileUpload: function(data,type,name) { var opts = { 'file':name.slice(0,name.lastIndexOf('.')), 'url':"/js/ueditor/jsp/uploader.jsp?action=uploaduser&dirName=comment&needCompress=true" }; if(type.indexOf('jpeg')>-1) type='image/jpg'; var text = window.atob(data.split(',')[1]); var ia = new Uint8Array(text.length); for (var i = 0; i < data.length; i++) { ia[i] = text.charCodeAt(i); }; var Builder = window.WebKitBlobBuilder || window.MozBlobBuilder; var blob; if (Builder) { var builder = new Builder(); builder.append(ia); blob = builder.getBlob(type); } else { blob = new window.Blob([ia], {type: type}); } var fd = new FormData(); fd.append(opts.file, blob); var xhr = new XMLHttpRequest(); xhr.addEventListener("load", opts.success, false); xhr.addEventListener("error", opts.error, false); xhr.open("POST", opts.url); xhr.send(fd); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { CommentDetail.everyUploadCount--; var ret = JSON.parse(xhr.responseText); console.log(ret); console.log(ret.state); if(ret.state=='SUCCESS'){ CommentDetail.uploadImg.push({"original":ret.original,"savepath":ret.savepath}); } if(CommentDetail.everyUploadCount==0){ layer.close(CommentDetail.layerLoadingIndex); } } }; }, delImage : function(obj,name){ console.log('删除前:',CommentDetail.uploadImg) for(var i=0;i<CommentDetail.uploadImg.length;i++){ var original = CommentDetail.uploadImg[i].original.slice(0,CommentDetail.uploadImg[i].original.lastIndexOf('.')); var delName = name.slice(0,name.lastIndexOf('.')); if(original == delName){ CommentDetail.uploadImg.splice(i,1); } } console.log('删除后:',CommentDetail.uploadImg) $(obj).parents('li').remove(); CommentDetail.uploadShowHide(); }, initSwiper : function (obj) { var img = $("#commentImgList").find('.li-img').find('img'); var index = $(obj).parents('li.li-img').index(); var html = ''; html += '<div class="swiper-container swiper-container-comment" id="swiperContainer" style="display:block;"><div class="swiper-wrapper">'; for(var i=0;i<img.length;i++){ html += '<div class="swiper-slide ui-flex justify-center center">' + '<img src="'+img[i].src+'" onclick="CommentDetail.closeSwiper()">' + '</div>'; } html += '</div><div class="swiper-pagination"></div></div>'; $('body').append(html); new Swiper ('#swiperContainer', { loop: true, initialSlide:index, pagination: '.swiper-pagination', paginationType : 'fraction' }) }, closeSwiper : function () { $("#swiperContainer").remove(); }, }; $(function () { CommentDetail.submitComment({obj:$("#btnSubmitComment")}); CommentDetail.imgFileUpload() });
B、HTML
<ul class="list" id="commentImgList" data-pswp-uid="1"> <li class="li-file"> <img src="images/input-file-default.png" alt="" style="width:100%;"> <input type="file" class="img-file" id="imgFileUpload" multiple/> </li> </ul> <a href="javascript:;" class="btn-submit" id="btnSubmitComment">提交</a>
C、megapix-image.js (https://github.com/stomita/ios-imagefile-megapixel)
/** * Mega pixel image rendering library for iOS6 Safari * * Fixes iOS6 Safari's image file rendering issue for large size image (over mega-pixel), * which causes unexpected subsampling when drawing it in canvas. * By using this library, you can safely render the image with proper stretching. * * Copyright (c) 2012 Shinichi Tomita <shinichi.tomita@gmail.com> * Released under the MIT license */ (function() { /** * Detect subsampling in loaded image. * In iOS, larger images than 2M pixels may be subsampled in rendering. */ function detectSubsampling(img) { var iw = img.naturalWidth, ih = img.naturalHeight; if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image var canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; var ctx = canvas.getContext('2d'); ctx.drawImage(img, -iw + 1, 0); // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering edge pixel or not. // if alpha value is 0 image is not covering, hence subsampled. return ctx.getImageData(0, 0, 1, 1).data[3] === 0; } else { return false; } } /** * Detecting vertical squash in loaded image. * Fixes a bug which squash image vertically while drawing into canvas for some images. */ function detectVerticalSquash(img, iw, ih) { var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = ih; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); var data = ctx.getImageData(0, 0, 1, ih).data; // search image edge pixel position in case it is squashed vertically. var sy = 0; var ey = ih; var py = ih; while (py > sy) { var alpha = data[(py - 1) * 4 + 3]; if (alpha === 0) { ey = py; } else { sy = py; } py = (ey + sy) >> 1; } var ratio = (py / ih); return (ratio===0)?1:ratio; } /** * Rendering image element (with resizing) and get its data URL */ function renderImageToDataURL(img, options, doSquash) { var canvas = document.createElement('canvas'); renderImageToCanvas(img, canvas, options, doSquash); return canvas.toDataURL("image/jpeg", options.quality || 0.8); } /** * Rendering image element (with resizing) into the canvas element */ function renderImageToCanvas(img, canvas, options, doSquash) { var iw = img.naturalWidth, ih = img.naturalHeight; if (!(iw+ih)) return; var width = options.width, height = options.height; var ctx = canvas.getContext('2d'); ctx.save(); transformCoordinate(canvas, ctx, width, height, options.orientation); var subsampled = detectSubsampling(img); if (subsampled) { iw /= 2; ih /= 2; } var d = 1024; // size of tiling canvas var tmpCanvas = document.createElement('canvas'); tmpCanvas.width = tmpCanvas.height = d; var tmpCtx = tmpCanvas.getContext('2d'); var vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1; var dw = Math.ceil(d * width / iw); var dh = Math.ceil(d * height / ih / vertSquashRatio); var sy = 0; var dy = 0; while (sy < ih) { var sx = 0; var dx = 0; while (sx < iw) { tmpCtx.clearRect(0, 0, d, d); tmpCtx.drawImage(img, -sx, -sy); ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh); sx += d; dx += dw; } sy += d; dy += dh; } ctx.restore(); tmpCanvas = tmpCtx = null; } /** * Transform canvas coordination according to specified frame size and orientation * Orientation value is from EXIF tag */ function transformCoordinate(canvas, ctx, width, height, orientation) { switch (orientation) { case 5: case 6: case 7: case 8: canvas.width = height; canvas.height = width; break; default: canvas.width = width; canvas.height = height; } switch (orientation) { case 2: // horizontal flip ctx.translate(width, 0); ctx.scale(-1, 1); break; case 3: // 180 rotate left ctx.translate(width, height); ctx.rotate(Math.PI); break; case 4: // vertical flip ctx.translate(0, height); ctx.scale(1, -1); break; case 5: // vertical flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.scale(1, -1); break; case 6: // 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(0, -height); break; case 7: // horizontal flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(width, -height); ctx.scale(-1, 1); break; case 8: // 90 rotate left ctx.rotate(-0.5 * Math.PI); ctx.translate(-width, 0); break; default: break; } } var URL = window.URL && window.URL.createObjectURL ? window.URL : window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null; /** * MegaPixImage class */ function MegaPixImage(srcImage) { if (window.Blob && srcImage instanceof Blob) { if (!URL) { throw Error("No createObjectURL function found to create blob url"); } var img = new Image(); img.src = URL.createObjectURL(srcImage); this.blob = srcImage; srcImage = img; } if (!srcImage.naturalWidth && !srcImage.naturalHeight) { var _this = this; srcImage.onload = srcImage.onerror = function() { var listeners = _this.imageLoadListeners; if (listeners) { _this.imageLoadListeners = null; for (var i=0, len=listeners.length; i<len; i++) { listeners[i](); } } }; this.imageLoadListeners = []; } this.srcImage = srcImage; } /** * Rendering megapix image into specified target element */ MegaPixImage.prototype.render = function(target, options, callback) { if (this.imageLoadListeners) { var _this = this; this.imageLoadListeners.push(function() { _this.render(target, options, callback); }); return; } options = options || {}; var imgWidth = this.srcImage.naturalWidth, imgHeight = this.srcImage.naturalHeight, width = options.width, height = options.height, maxWidth = options.maxWidth, maxHeight = options.maxHeight, doSquash = !this.blob || this.blob.type === 'image/jpeg'; if (width && !height) { height = (imgHeight * width / imgWidth) << 0; } else if (height && !width) { width = (imgWidth * height / imgHeight) << 0; } else { width = imgWidth; height = imgHeight; } if (maxWidth && width > maxWidth) { width = maxWidth; height = (imgHeight * width / imgWidth) << 0; } if (maxHeight && height > maxHeight) { height = maxHeight; width = (imgWidth * height / imgHeight) << 0; } var opt = { width : width, height : height }; for (var k in options) opt[k] = options[k]; var tagName = target.tagName.toLowerCase(); if (tagName === 'img') { target.src = renderImageToDataURL(this.srcImage, opt, doSquash); } else if (tagName === 'canvas') { renderImageToCanvas(this.srcImage, target, opt, doSquash); } if (typeof this.onrender === 'function') { this.onrender(target); } if (callback) { callback(); } if (this.blob) { this.blob = null; URL.revokeObjectURL(this.srcImage.src); } }; /** * Export class to global */ if (typeof define === 'function' && define.amd) { define([], function() { return MegaPixImage; }); // for AMD loader } else if (typeof exports === 'object') { module.exports = MegaPixImage; // for CommonJS } else { this.MegaPixImage = MegaPixImage; } })();