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" οnclick="CommentDetail.initSwiper(this)" style="width: 100%;"></a><i class="icon-del" οnclick="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" οnclick="CommentDetail.initSwiper(this)" style="height: 100%;"></a><i class="icon-del" οnclick="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+'" οnclick="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 imagevar 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 canvasvar 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 flipctx.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 flipctx.translate(0, height);ctx.scale(1, -1);break;case 5:// vertical flip + 90 rotate rightctx.rotate(0.5 * Math.PI);ctx.scale(1, -1);break;case 6:// 90 rotate rightctx.rotate(0.5 * Math.PI);ctx.translate(0, -height);break;case 7:// horizontal flip + 90 rotate rightctx.rotate(0.5 * Math.PI);ctx.translate(width, -height);ctx.scale(-1, 1);break;case 8:// 90 rotate leftctx.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;}})();

 

转载于:https://www.cnblogs.com/ilovexiaoming/p/7845315.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/281862.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

node安装问题

1.最好安装到默认路径&#xff0c;手贱安到了D盘&#xff0c;升级npm各种出错。 明明升级成功&#xff0c;查看版本时&#xff0c;确显示依然是老的版本。 原因&#xff1a;升级的是C盘的node_modules中的npm&#xff0c;执行时确是D盘node自带的npm&#xff0c;不知道为啥。。…

全新升级的AOP框架Dora.Interception[汇总,共6篇]

多年之前利用IL Emit写了一个名为Dora.Interception的AOP框架。前几天利用Roslyn的Source Generator对自己为公司写的一个GraphQL框架进行改造&#xff0c;性能得到显著的提高&#xff0c;觉得类似的机制同样可以用在AOP框架上&#xff0c;实验证明这样的实现方式不仅仅极大地改…

java string转decimal_java中string转bigdecimal的例子

小编知道在java中数据类型非常 的严格了&#xff0c;我们如果一个地方不小心就会导致应用出问题了&#xff0c;今天 小编就在string 转BigDecimal上碰到了一些问题&#xff0c;下面整理了几个例子大家一起来看看。例子1,string 转BigDecimalpublic class Test{public static vo…

通过url来设置log4j的记录级别

2019独角兽企业重金招聘Python工程师标准>>> 直接看代码。 import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotati…

通过用户模型,对数据库进行增删改查操作

增加&#xff1a;user db.session.add(user)db.session.commit() #增加 user User(username JACKSON,password0328 ) db.session.add(user) db.session.commit() 查询&#xff1a;User.query.filter(User.username mis1114).first() #查询 userUser.query.filter(User.usern…

Android OpenGL ES(七)----理解纹理与纹理过滤

1.理解纹理 OpenGL中的纹理能够用来表示图像。照片&#xff0c;甚至由一个数学算法生成的分形数据。每一个二维的纹理都由很多小的纹理元素组成。它们是小块的数据&#xff0c;类似于我们前面讨论过的片段和像素。要使用纹理&#xff0c;最经常使用的方式是直接从一个图像文件载…

WPF 基础控件之托盘

WPF 基础控件之托盘控件名&#xff1a;NotifyIcon作者&#xff1a; WPFDevelopersOrg - 吴锋|驚鏵原文链接&#xff1a; https://github.com/WPFDevelopersOrg/WPFDevelopers框架使用大于等于.NET40。Visual Studio 2022。项目使用 MIT 开源许可协议。新建NotifyIcon自定义…

java 匿名 异常_JAVA类(内部类、匿名内部类、异常、自定义异常)

内部类package AA;public class类 {int de123;StringBuffer deenewStringBuffer();public class成员内部类{public voidff() {System.out.println("这是成员内部类方法");}}/*1.可以访问外部类所有的成员&#xff0c;包括被声明为私有(private)的&#xff1b;2.可以使…

ASP.NET 多环境下配置文件web.config的灵活配置---转

注意&#xff1a;本功能在.Net Core中已经不可用&#xff0c;暂时需手动修改web.config中的信息&#xff0c;或者将其设置在appsettings.XXX.json中&#xff0c;然后再使用web.config中的环境变量来制定使用的具体appsettings文件。 转自&#xff1a;https://www.cnblogs.com/h…

英语之各类人群

工作狂&#xff1a;workaholic 月光族&#xff1a;moonlight group 电灯泡&#xff1a;third wheel 菜鸟&#xff1a;newbie 夜猫子&#xff1a;night owl 路痴&#xff1a;somebody has no sense of derection 宅男宅女&#xff1a;homebody 时尚的潮人&#xff1a;trend sett…

Wget CVE-2014-4877:FTP 符号链接任意文件系统访问

Wget 爆出 CVE-2014-4877 漏洞&#xff1a;FTP 符号链接任意文件系统访问。 Package: wgetVersion: 1.15-1Severity: important Upstream fix&#xff1a; http://git.savannah.gnu.org/cgit/wget.git/commit/?id18b0979357ed7dc4e11d4f2b1d7e0f5932d82aa7 References&#xf…

JavaScript 学习提升

javascript 技能提升 理解闭包 闭包&#xff0c;官方对闭包的解释是&#xff1a;一个拥有许多变量和绑定了这些变量的环境的表达式&#xff08;通常是一个函数&#xff09;&#xff0c;因而这些变量也是该表达式的一部分。闭包的特点&#xff1a;1. 作为一个函数变量的一个引用…

Uranium UI Kit

Uranium UI Kit控件名&#xff1a;Uranium UI Ki作者&#xff1a;enisn原文链接&#xff1a; https://github.com/enisn/UraniumUI项目使用 Apache-2.0 开源许可协议。Uranium 是用于 .NET MAUI 的免费和开源 UI 工具包。它提供了一组控件和实用程序来构建现代应用程序。它建…

数据库监控框架 oneproxy-monitor 开源了

OneProxy-Monitor 是数据库监控的框架&#xff0c;通过这个框架可以快速的开发出一款数据库的监控软件。目前已经在这个框架下面开发出来了sql server的监控软件oneproxy-for-sqlserver&#xff0c; postgresql的监控软件oneproxy-for-postgresql。并且还可以作为协议成的调试软…

java nio epoll_Java NIO 选择器(Selector)的内部实现(poll epoll)

http://blog.csdn.net/hsuxu/article/details/9876983之前强调这么多关于linux内核的poll及epoll&#xff0c;无非是想让大家先有个认识&#xff1a;Java NIO中的选择器依赖操作系统内核的这些系统调用&#xff0c;我们这里只讲解与linux内核相关的NIO实现&#xff0c;当然&…

Next.js 7发布,构建速度提升40%

Next.js团队发布了其开源React框架的7版本。该版本的Next.js主要是改善整体的开发体验&#xff0c;包括启动速度提升57%、开发时的构建速度提升40%、改进错误报告和WebAssembly支持。\\Next.js是一个React框架&#xff0c;它的主要目标是在生产环境中提供出色的性能和良好的开发…

《Java多线程编程核心技术》读后感(十五)

线程的状态 线程对象在不同的运行时期有不同的状态&#xff0c;状态信息就存在与State枚举类中。 验证New,Runnable&#xff0c;Terminated new:线程实例化后还从未执行start()方法时的状态 runnable&#xff1a;线程进入运行的状态 terminated&#xff1a;线程被销毁时的状态 …

队列(queue)

队列(queue)和栈一样支持push和pop两个操作。但与栈不同的是,pop两个操作。但与栈的不同的是&#xff0c;pop完成的不是取出最顶端的元素&#xff0c;而是最底端的元素。也就是说最初放入的元素能够最先被取出&#xff08;这种行为被叫做FIFO:First In First Out&#xff0c;即…

一题多解,ASP.NET Core应用启动初始化的N种方案[上篇]

ASP.NET Core应用本质上就是一个由中间件构成的管道&#xff0c;承载系统将应用承载于一个托管进程中运行起来&#xff0c;其核心任务就是将这个管道构建起来。在ASP.NET Core的发展历史上先后出现了三种应用承载的编程方式&#xff0c;而且后一种编程模式都提供了针对之前编程…

java程序猿面试问缺点怎么回答_JAVA程序员面试32问,你能回答多少题

第一&#xff0c;谈谈final&#xff0c; finally&#xff0c; finalize的区别。第二&#xff0c;Anonymous Inner Class (匿名内部类) 是否可以extends(继承)其它类&#xff0c;是否可以implements(实现)interface(接口)&#xff1f;第三&#xff0c;Static Nested Class 和 In…