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="data: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;
} })();

h5 端图片上传-模拟多张上传的更多相关文章

  1. h5 端图片上传

    1.upload.js (function($) { $.extend($.fn, { images : new Array(), initImages:function (images) { $.e ...

  2. h5 js 图片预览并判断 ajax上传

    //建立一個可存取到該file的url function getObjectURL(file) { var url = null; if (window.createObjectURL != unde ...

  3. 移动端H5实现图片上传

    移动端H5实现图片上传 https://segmentfault.com/a/1190000010034177

  4. 在浏览器端用H5实现图片压缩上传

    一.需求的场景: 在我们的需求中需要有一个在手机浏览器端,用户实现上传证件照片的功能,我们第一版上了一个最简版,直接让用户在本地选择图片,然后上传到公司公共的服务器上. 功能实现后我们发现一个问题,公 ...

  5. 移动前端—H5实现图片先压缩再上传

    在做移动端图片上传的时候,用户传的都是手机本地图片,而本地图片一般都相对比较大,拿iphone6来说,平时拍很多图片都是一两M的,如果直接这样上传,那图片就太大了,如果用户用的是移动流量,完全把图片上 ...

  6. 基于h5的图片无刷新上传(uploadifive)

    基于h5的图片无刷新上传(uploadifive) uploadifive简介 了解uploadify之前,首先了解来一下什么是uploadify,uploadfy官网,uploadify和uploa ...

  7. 项目回顾1-图片上传-form表单还是base64-前端图片压缩

    第一个项目终于上线了,是一个叫亲青筹的公益众筹平台,微信端,电脑端还有后台界面大部分都是我完成的,几个月过来,感觉收获了很多,觉得要总结一下. 首先想到的是图片上传的问题.在通常表单数据都是ajax上 ...

  8. angularJS+Ionic移动端图片上传的解决办法

    前端开发中经常会碰到图片上传的问题,网上的解决办法很多,可是有些图片上传的插件会有一些附属的插件,因此因为一个图片上传的问题可能额需要引入其他插件到项目中,久而久之项目会不伦不类,有时候插件之间也会有 ...

  9. 基于vue + axios + lrz.js 微信端图片压缩上传

    业务场景 微信端项目是基于Vux + Axios构建的,关于图片上传的业务场景有以下几点需求: 1.单张图片上传(如个人头像,实名认证等业务) 2.多张图片上传(如某类工单记录) 3.上传图片时期望能 ...

随机推荐

  1. 安卓TP驱动开发

    转自 blog.csdn.net/dddxxxx/article/details/54312415

  2. cyclone iv中DDR2的本地接口时序

    本地接口 信号名 方向  描述  local_burstbegin input 如果local_ready无效不起作用.IP核在local_write_req为高时,在phy_clk上升沿采样.当lo ...

  3. AngularJS实战之ng-repeat的详细用法

    一.基本语法 {{$index}}:获取元素的下标. {{$first}}:判断当前元素是否是第一个元素,是则为true,否则:false: {{$last}}:判断当前元素是否是最后一个元素,是则为 ...

  4. #微码分享#C++变参字符串格式化函数format_string

    在C和C++中,变参格式化函数虽然非类型安全,但却十分便利,因为得到广泛使用.对于常见的size_t类型要用“%zu”,ssize_t用”%zd“,int64_t用“% ”PRId64,uint64_ ...

  5. 笔记:IIFE 立即执行的函数表达式 +function ($) { }(window.jQuery);

    在Bootstrap源码(具体请看<Bootstrap源码解析1>)和其他jQuery插件经常看到如下的写法: +function ($) { }(window.jQuery); 这种写法 ...

  6. leetcode - [1]Reverse Words in a String

    Question: Reverse Words in a String Given an input string, reverse the string word by word. For exam ...

  7. noip第27课作业

    1. 繁忙的都市 [问题描述] 城市C是一个非常繁忙的大都市,城市中的道路十分的拥挤,于是市长决定对其中的道路进行改造.城市C的道路是这样分布的:城市中有n个交叉路口,有些交叉路口之间有道路相连,两个 ...

  8. java中逗号分隔的字符串和List相互转换

    1.将逗号分隔的字符串转换为List String str = "a,b,c"; List<String> result = Arrays.asList(str.spl ...

  9. hdu 4704 Sum 【费马小定理】

    题目 题意:将N拆分成1-n个数,问有多少种组成方法. 例如:N=4,将N拆分成1个数,结果就是4:将N拆分成2个数,结果就是3(即:1+3,2+2,3+1)--1+3和3+1这个算两个,则这个就是组 ...

  10. PCA原理分析

    动机 在机器学习领域中,我们常常会遇到维数很高的数据,有些数据的特征维度高达上百万维,很显然这样的数据是无法直接计算的,而且维度这么高,其中包含的信息一定有冗余,这时就需要进行降维,总的来说,我们降维 ...