发布一个图片上传插件,带图片上传后生成预览图片
插件代码:
/**
* zx-upload.js v1.0.0
* 上传插件
* http://www.*.com/
*
* Copyright 2018-2028 zxhj963
*
* Released on: 2018/7/21
*/
; (function ($, window, document, undefined) {
"use strict";
var defaults = {
isLayer:true,
maxCount: 5,
curCount: 0,
urls: '',
limitWidth: 500,
limitHeight: 500,
viewWidth: 80,
viewHeight: 80,
errViewImg:'../images/noimage.gif',
savePath: '/upload/upload/upload/',
saveServerUrl: "uploadBase64Img.asp"
};
function Upload($ele, options) {
this.$ele = $ele;
this.options = $.extend({}, defaults, options);
console.log(this.options)
this.init();
}
Upload.prototype = {
constructor: Upload,
init: function () {
this.renderViewBox();
this.bindAddEven();
this.bindEditEven();
this.bindDelEven();
},
clearViewItem: function () {
this.$ele.find('.view-item').remove(); //清除所有的view-item
},
showUploadBtn: function () {
this.$ele.children('.zx-view-box').children('label.button').show(); //显示上传按钮
},
hideUploadBtn: function () {
this.$ele.children('.zx-view-box').children('label.button').hide(); //隐藏上传按钮
},
resizeImgSize: function (originWidth, originHeight, maxWidth, maxHeight) {
var targetWidth = originWidth, targetHeight = originHeight;
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > maxWidth / maxHeight) {
// 更宽,按照宽度限定尺寸
targetWidth = maxWidth;
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
} else {
targetHeight = maxHeight;
targetWidth = Math.round(maxHeight * (originWidth / originHeight));
}
}
else {
targetWidth = originWidth;
targetHeight = originHeight;
}
return {
w: targetWidth,
h: targetHeight
}
},
getImageSize: function (url,callback) {
var img = new Image();
img.src = url;
// 如果图片被缓存,则直接返回缓存数据
if (img.complete) {
var ret = {
w: img.width,
h: img.height
};
callback(ret)
} else {
// 完全加载完毕的事件
img.onload = function () {
var ret = {
w: img.width,
h: img.height
};
callback(ret)
}
}
return ret;
},
getImgUrlBase64: function (imageObj, targetSize) {
var canvas = document.createElement('canvas');
//创建预览图片
canvas.width = targetSize.w;
canvas.height = targetSize.h;
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布
ctx.drawImage(imageObj, 0, 0, canvas.width, canvas.height);
var Img64 = canvas.toDataURL(); // 压缩后的base64串
return Img64;
},
getInputUrls: function () {
//获取文本框中的链接和链接数量
var that = this,
urls = that.$ele.children('input.zx-urlInput').val(),
urls_arr = urls.split(','),
counts = (urls == '') ? 0 : urls_arr.length,
maxCount = this.options.maxCount;
if (counts >= maxCount) {
var temp_arr = [];
urls_arr.forEach(function (e, i) {
if (i < maxCount) { temp_arr.push(e); }
});
urls = temp_arr.join(',');
counts = maxCount;
that.hideUploadBtn();
}
else {
that.showUploadBtn();
}
that.$ele.children('input.zx-urlInput').val(urls);
return {
urls: urls,
counts: counts
};
},
renderViewBox: function () {
var that = this;
that.clearViewItem();
var curUrls = that.getInputUrls().urls;
var curCount = that.getInputUrls().counts;
if (curCount > 0) {
var arr_Urls = curUrls.split(',');
arr_Urls.forEach(function (e, i) {
if (i < that.options.maxCount) {
var viewImg64 = that.options.errViewImg;
var viewItemHtml = '';
that.$ele.children('.zx-view-box').append(viewItemHtml);
//e为文本框中的图片链接地址,需转换成viewImg64的预览图片地址
that.getImageSize(e, function (ret) {
var viewImg64Size = that.resizeImgSize(ret.w, ret.h, that.options.viewWidth, that.options.viewHeight);
var imgView = new Image();
imgView.src = e;
imgView.onload = function () {
var viewImg64 = '';
if (imgView.fileSize > 0 || (imgView.width > 0 && imgView.height > 0)) {
viewImg64 = that.getImgUrlBase64(imgView, viewImg64Size)
} else {
viewImg64 = that.options.errViewImg;
}
that.$ele.children('.zx-view-box').find('.view-item').eq(i).children('img').attr('src', viewImg64);
}
});
} else {
}
});
}
},
bindAddEven: function () {
var that = this;
var newUrls = '', msg='';
that.$ele.children('.zx-view-box').on('change', '.zx-fileInput', function () {
var curUrls = that.getInputUrls().urls;
var curCount = that.getInputUrls().counts;
newUrls = curUrls;
if (curCount >= that.options.maxCount) {
return false;
}
else {
var file = this.files[0];
var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
if (!rFilter.test(file.type)) {
if (that.options.isLayer) {
msg = '数据错误,提交的数据不是文件!';
if (that.options.isLayer) {
layer.alert(msg, { icon: 2 });
} else {
alert(msg);
}
} else {
msg = '文件格式不正确!';
if (that.options.isLayer) {
layer.alert(msg, { icon: 2 });
} else {
alert(msg);
}
}
return false;
}
else {
if (!!file) {
//是图片文件,开始上传到服务器
var reader = new FileReader();
reader.readAsDataURL(file); // 图片文件转换为base64
reader.onload = function () { // 文件加载完成
var def_url = this.result; //图片原图的base64链接
var image = new Image();
image.src = def_url;
image.onload = function () {
var originWidth = this.width, originHeight = this.height; // 图片原始尺寸
var limitWidth = that.options.limitWidth, limitHeight = that.options.limitHeight; // 保存图片的最大尺寸限制
var targetSize = that.resizeImgSize(originWidth, originHeight, limitWidth, limitHeight); // 图片尺寸超过限制,调整尺寸
var targetImg64 = that.getImgUrlBase64(image, targetSize);
var formData = new FormData();
formData.append("imgUrl", targetImg64);
formData.append("savePath", that.options.savePath);
$.ajax({
type: "POST",
url: that.options.saveServerUrl,
data: formData,
dataType: "json", //声明成功使用json数据类型回调
//如果传递的是FormData数据类型,那么下来的三个参数是必须的,否则会报错
cache: false, //默认是true,但是一般不做缓存
processData: false, //用于对data参数进行序列化处理,这里必须false;如果是true,就会将FormData转换为String类型
contentType: false, //一些文件上传http协议的关系,自行百度,如果上传的有文件,那么只能设置为false
success: function (ret) { //请求成功后的回调函数
if (ret.code == 200) {
msg = ' 上传成功!
先贴上代码!
插件使用方法:
本插件需要依赖jquery库,我用的是jquery-1.12.4.js,另外layer插件可以按您的需要引用,也可以不引用,但是如果options的参数中的isLayer如果设置为true时,则必须引入layer库
先引用jquery.js库,我用的是jquery-1.12.4.js,
再引入layer.js库
再引入pintuer UI,不引用则需要按实际需要调整样式;
项目中调用插件方法:
<script type="text/javascript" src="../js/jquery.zx-upload.js">script>
<script type="text/javascript">
$(function () {
var upload1 = $('.upload-box-1').ZX_upload({
maxCount: 1
});
var upload2 = $('.upload-box-2').ZX_upload({
maxCount: 5
});
});
script>
缺点:图片不能多张图片上传,每次只能上传一张图片。
**特别注意**
1. 上传图片的接口,是以二进制流的格式传递的,所以在获取数据时要注意。(ASP后台建议使用各类无组件文件上传类,如:AnUpLoad上传类等,有需要的可以给我留言)
2. 文件上传接口需要提供的数据格式为json格式,上传成功需要得到{code:200,msg:""},msg中为上传后的图片链接,如果上传失败,则需要将code给成其他值既可以。
Mark: 2018/7/21 18:05 因时间关系 编辑功能 还在开发中。