h5 端图片上传
1、upload.js
(function($) {
$.extend($.fn, {
images : new Array(),
initImages:function (images) {
$.each(images,function (index,value) {
$(this).images.push(value);
var $img = $('<div><div class="try-report-add thumb"><img class="dataImg" src='+ConstUtil.get("PIC_DOMAIN")+value+'></div>' +
'<img onclick="$(this).delImage(\''+value+'\',this)" src="/pages/prod/activity/try/images/try-delete.png"></div>');
$("#upImg").append($img);
})
},
getImages: function () {
return $(this).images;
},
delImage: function (url,e) {
for(i in $(this).images){
if(url == $(this).images[i]){
$(this).images.splice(i,1);
}
}
$(e).parent().remove();
$("#upload").show();
},
fileUpload: function(opts) {
this.each(function() {
var $self = $(this);
var quality = opts.quality ? opts.quality / 50 : 0.5;
var dom = {
"fileToUpload": $self.find(".fileToUpload"),
"thumb": $self.find(".thumb"),
"progress": $self.find(".upload-progress")
};
var funs = {
bindEvent: function() {
console.log(dom.fileToUpload)
// $self.click(function(){
// dom.fileToUpload.click(function (event) {
// event.stopPropagation();//防止事件冒泡
// }).click();
// });
dom.fileToUpload.on("change", function() {
if($(this).images.length>=opts.maxNum){
alert("最多只能上传"+opts.maxNum+"图片");
return;
}
funs.fileSelect(this);
});
},
fileSelect: function(obj) {
for(var i=0;i<obj.files.length;i++) {
var file = obj.files[i];
var reader = new FileReader();
reader.onload = function () {
var image = new Image();
image.src = reader.result;
image.onload = function () {
var wdh = Number(image.width)>Number(image.heihgt)? true : false;
var data = funs.compress(this);
funs.fileUpload(data, file.type,wdh);
};
};
reader.readAsDataURL(file);
}
},
fileUpload: function(data,type,wdh) {
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) {
var ret = JSON.parse(xhr.responseText);
console.log(ret);
console.log(ret.state);
if(ret.state=='SUCCESS'){
var commentListLiHeight = Number((window.screen.width)*0.92*0.3).toFixed(1);
if(wdh){
var $img = $('<li class="li-img"><a style="height: '+commentListLiHeight+'px;" href="javascript:;"><img class="dataImg" onclick="CommentDetail.initSwiper(this)" style="width: 100%;" src='+ret.url+'></a>' +
'<i class="icon-del" onclick="$(this).delImage(\''+ret.savepath+'\',this)"></i></li>');
}else{
var $img = $('<li class="li-img"><a style="height: '+commentListLiHeight+'px;" href="javascript:;"><img class="dataImg" onclick="CommentDetail.initSwiper(this)" style="height: 100%;" src='+ret.url+'></a>' +
'<i class="icon-del" onclick="$(this).delImage(\''+ret.savepath+'\',this)"></i></li>');
}
$("#upImg").prepend($img);
$(this).images.push(ret.savepath);
if($(this).images.length==opts.maxNum){
$("#upload").hide();
}
}
}
};
},
compress: function(img) {
var canvas = document.createElement("canvas"),
ctx = canvas.getContext('2d'),
tCanvas = document.createElement("canvas"),//瓦片canvas
tctx = tCanvas.getContext("2d");
var initSize = img.src.length;
var width = img.width;
var height = img.height;
//如果图片大于四百万像素,计算压缩比并将大小压至400万以下
var ratio;
if ((ratio = width * height / 4000000)>1) {
ratio = Math.sqrt(ratio);
width /= ratio;
height /= ratio;
}else {
ratio = 1;
}
canvas.width = width;
canvas.height = height;
// 铺底色
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
//如果图片像素大于100万则使用瓦片绘制
var count;
if ((count = width * height / 1000000) > 1) {
count = ~~(Math.sqrt(count)+1); //计算要分成多少块瓦片
// 计算每块瓦片的宽和高
var nw = ~~(width / count);
var nh = ~~(height / count);
tCanvas.width = nw;
tCanvas.height = nh;
for (var i = 0; i < count; i++) {
for (var j = 0; j < count; j++) {
tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
}
}
} else {
ctx.drawImage(img, 0, 0, width, height);
}
//进行最小压缩
console.log('*****',quality)
var ndata = canvas.toDataURL('image/jpeg', quality);
console.log('压缩前:' + initSize);
console.log('压缩后:' + ndata.length);
console.log('压缩率:' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
return ndata;
}
};
funs.bindEvent();
});
}
});
})($);
2、调用
var CommentDetail = {
bindEvent : function () {
var url ="/js/ueditor/jsp/uploader.jsp?action=uploaduser&dirName=comment&needCompress=true"; //上传路径
$("#upload").fileUpload({
"url": url,
"file": "comment",
"maxNum": 6
});
}
3、html
<div class="try-my-push clearfix">
<ul class="list" id="upImg">
<!--<iframe id="upframe" name="upframe" src="" style="display:none;"> </iframe>-->
<li class="try-report-btn" id="upload">
<a href="javascript:;">
<img src="data:images/input-file-default.png" alt="" width="100%;"style="max-width: 100%;"> <!--<form action="/plugins/ueditor/jsp/uploader.jsp?action=uploaduser&dirName=headimg&needCompress=true"-->
<!--method="POST" id="form1" enctype="multipart/form-data">-->
<input type="file" id="front-file" class="fileToUpload img-file">
</a>
<!--</form>-->
</li>
</ul>
</div>
可以实现单张图片压缩后上传,无法多张上传,通过for循环 多次异步请求,结果有可能返回同一个结果或者返回多个结果,但是是同一个图片。
h5 端图片上传的更多相关文章
- h5 端图片上传-模拟多张上传
1.由于后端的限制,上传图片到服务器只能的一张一张传2.显示图片预览是本地的图片3.根据服务器返回的结果拿到相应的路径保存到提交评论的接口中4.删除的时候,需要删除对应的路径,不要把删除的提交到评论的 ...
- 移动端H5实现图片上传
移动端H5实现图片上传 https://segmentfault.com/a/1190000010034177
- angularJS+Ionic移动端图片上传的解决办法
前端开发中经常会碰到图片上传的问题,网上的解决办法很多,可是有些图片上传的插件会有一些附属的插件,因此因为一个图片上传的问题可能额需要引入其他插件到项目中,久而久之项目会不伦不类,有时候插件之间也会有 ...
- 移动端图片上传解决方案localResizeIMG先压缩后ajax无刷新上传
现在科技太发达,移动设备像素越来越高,随便一张照片2M+,但是要做移动端图片上传和pc上略有不同,移动端你不能去限制图片大小,让用户先处理图片再上传,这样不现实.所以理解的解决方案就是在上传先进行图片 ...
- vue+axios实现移动端图片上传
在利用vue做一些H5页面时,或多或少会遇到有图片上传的操作,主要是运用html5里面的input[type=file]来实现,传递到后端的数据是以二进制的格式传递,所以上传图片的请求与普通的请求稍微 ...
- 用html5文件api实现移动端图片上传&预览效果
想要用h5在移动端实现图片上传&预览效果,首先要了解html5的文件api相关知识(所有api只列举本功能所需): 1.Blob对象 Blob表示原始二进制数据,Html5的file对象就继 ...
- HTML5移动端图片上传模块
上传图片的功能是极为常用的,之前做过一个移动端上传文件的功能(基于jquery的),总结梳理一下. html <div class="uploadPic clearBox"& ...
- H5 实现图片上传预览
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...
- Js 之移动端图片上传插件mbUploadify
一.下载 https://pan.baidu.com/s/1NEL4tkHoK4ydqdMi_hgWcw 提取码:vx7e 二.Demo示例 <div class="weui_uplo ...
随机推荐
- yersinia的DHCP池耗尽断网攻击
http://jingyan.baidu.com/article/0eb457e5045bd703f1a9051d.html yersinia -G
- 控件无法安装的问题-Unable to execute file
官方网站:http://www.ncmem.com/ 产品首页:http://www.ncmem.com/webplug/wordpaster/ 产品介绍:http://www.cnblogs.com ...
- MySQL Yum存储库 安装、升级、集群
添加MySQL Yum存储库 首先,将MySQL Yum存储库添加到系统的存储库列表中.按着这些次序: 在http://dev.mysql.com/downloads/repo/yum/上转到MySQ ...
- HDU1072 Nightmare(BFS) 2016-07-24 14:02 40人阅读 评论(0) 收藏
Nightmare Problem Description Ignatius had a nightmare last night. He found himself in a labyrinth w ...
- 简便方法搞定第三方SDK的Jar包在DelphiXE5中的引入
简便方法搞定第三方SDK的Jar包在DelphiXE5中的引入 (2014-02-21 17:30:17) 转载▼ 标签: android delphi xe5 jar sdk 分类: 编程杂集 折腾 ...
- Jesery客户端工具类
public class JerseyClientUtil { public static<T> T sendMsg(String url,Object object,Class<T ...
- asp.net mvc5 分析器错误消息: 未能加载类型“XXX.MvcApplication”
描述 今天忽然碰到一个这个错误: “/”应用程序中的服务器错误. 分析器错误 说明: 在分析向此请求提供服务所需资源时出错.请检查下列特定分析错误详细信息并适当地修改源文件. 分析器错误消息: 未能加 ...
- vs2017 xamarin新建单独UWP类库提示不兼容
One or more projects are incompatible with UAP,Version=v10.0 (win10-arm). One or more projects are i ...
- 基于VMware Workstation搭建开发服务器
基于VMware Workstation搭建开发服务器 文章为本人原创,转载请联系作者并注明出处.晓松 源URL: https://www.jianshu.com/p/e62ab7de0124 我 ...
- day 113 爬虫框架
基础配置