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.pswp.cn/news/281862.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/281862.shtml
英文地址,請注明出處:http://en.pswp.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…