jquery-rockupload.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /**
  2. * 无刷新上传
  3. * createname:雨中磐石
  4. * homeurl:http://www.rockoa.com/
  5. * Copyright (c) 2016 rainrock (xh829.com)
  6. * Date:2016-01-01
  7. */
  8. (function ($) {
  9. maxupgloble = 0;
  10. function rockupload(opts){
  11. var me = this;
  12. var opts = js.apply({inputfile:'',initpdbool:false,initremove:true,uptype:'*',maxsize:5,onchange:function(){},onchangebefore:function(){},upurl:'',onprogress:function(){},urlparams:{},updir:'',onsuccess:function(){},quality:0.7,xu:0,fileallarr:[],autoup:true,oldids:'',
  13. onerror:function(){},fileidinput:'fileid',
  14. onabort:function(){},
  15. allsuccess:function(){}
  16. },opts);
  17. this._init=function(){
  18. for(var a in opts)this[a]=opts[a];
  19. //加载最大可上传大小
  20. if(maxupgloble==0)$.getJSON(js.apiurl('login','getmaxup'),function(res){
  21. try{
  22. if(res.code==200){
  23. var maxup = parseFloat(res.data.maxup);
  24. me.maxsize= maxup;
  25. maxupgloble = maxup;
  26. }}catch(e){}
  27. });
  28. if(maxupgloble>0)this.maxsize= maxupgloble;
  29. if(!this.autoup)return;
  30. if(this.initremove){
  31. $('#'+this.inputfile+'').parent().remove();
  32. var s='<form style="display:none;height:0px;width:0px" name="form_'+this.inputfile+'"><input type="file" id="'+this.inputfile+'"></form>';
  33. $('body').append(s);
  34. }
  35. $('#'+this.inputfile+'').change(function(){
  36. me.change(this);
  37. });
  38. };
  39. this.reset=function(){
  40. if(!this.autoup)return;
  41. var fids = 'form_'+this.inputfile+'';
  42. if(document[fids])document[fids].reset();
  43. };
  44. this.setparams=function(ars){
  45. this.oparams = js.apply({uptype:this.uptype}, ars);
  46. this.uptype=this.oparams.uptype;
  47. };
  48. this.setuptype=function(lx){
  49. this.uptype = lx;
  50. };
  51. this.setupurl=function(ul){
  52. this.upurl = ul;
  53. };
  54. this.click=function(ars){
  55. if(this.upbool)return;
  56. this.setparams(ars);
  57. get(this.inputfile).click();
  58. };
  59. this.clear=function(){
  60. this.fileallarr = [];
  61. this.filearr = {};
  62. this.xu = 0;
  63. $('#'+this.fileview+'').html('');
  64. };
  65. this.change=function(o1){
  66. if(!o1.files){
  67. js.msg('msg','当前浏览器不支持上传1');
  68. return;
  69. }
  70. var f = o1.files[0];
  71. if(!f || f.name=='/')return;
  72. var a = {filename:f.name,filesize:f.size,filesizecn:js.formatsize(f.size)};
  73. if(a.filesize<=0){
  74. js.msg('msg',''+f.name+'不存在');
  75. return;
  76. }
  77. if(this.isfields(a))return;
  78. if(f.size>this.maxsize*1024*1024){
  79. this.reset();
  80. js.msg('msg','文件不能超过'+this.maxsize+'MB,当前文件'+a.filesizecn+'');
  81. return;
  82. }
  83. var filename = f.name;
  84. var fileext = filename.substr(filename.lastIndexOf('.')+1).toLowerCase();
  85. if(!this.uptype)this.uptype='*';
  86. if(this.uptype=='image')this.uptype='jpg,gif,png,bmp,jpeg';
  87. if(this.uptype=='word')this.uptype='doc,docx,pdf,xls,xlsx,ppt,pptx,txt';
  88. if(this.uptype!='*'){
  89. var upss=','+this.uptype+',';
  90. if(upss.indexOf(','+fileext+',')<0){
  91. js.msg('msg','禁止文件类型,请选择'+this.uptype+'');
  92. return;
  93. }
  94. }
  95. var nstr = this.onchangebefore(f);
  96. if(nstr){js.msg('msg',nstr);return;}
  97. a.fileext = fileext;
  98. a.isimg = js.isimg(fileext);
  99. if(a.isimg)a.imgviewurl = this.getimgview(o1);
  100. a.xu = this.xu;
  101. a.f = f;
  102. for(var i in this.oparams)a[i]=this.oparams[i];
  103. this.filearr = a;
  104. var zc=this.fileallarr.push(a);
  105. //如果是图片压缩一下超过1M
  106. if(f.size>1024*1024 && a.isimg && this.quality<1){
  107. this.compressimg(a.imgviewurl,f,function(nf){
  108. a.filesize = nf.size;
  109. a.filesizecn = js.formatsize(nf.size);
  110. me.fileallarr[zc-1].f = nf;
  111. me.nnonchagn(a, nf, zc);
  112. });
  113. }else{
  114. this.nnonchagn(a, f, zc);
  115. }
  116. };
  117. this.nnonchagn=function(a,f,zc){
  118. this.xu++;
  119. this.onchange(a);
  120. this.reset();
  121. if(!this.autoup){
  122. var s='<div style="padding:3px;font-size:14px;border-bottom:1px #dddddd solid"><font>'+a.filename+'</font>('+a.filesizecn+')&nbsp;<span style="color:#ff6600" id="'+this.fileview+'_'+a.xu+'"></span>&nbsp;<a oi="'+(zc-1)+'" id="gm'+this.fileview+'_'+a.xu+'" href="javascript:;">改名</a>&nbsp;<a onclick="$(this).parent().remove()" href="javascript:;">×</a></div>';
  123. $('#'+this.fileview+'').append(s);
  124. $('#gm'+this.fileview+'_'+a.xu+'').click(function(){
  125. me.s_gaiming(this);
  126. });
  127. return;
  128. }
  129. this._startup(f);
  130. };
  131. this.s_gaiming=function(o1){
  132. var o,oi,one,fa;
  133. o = $(o1);
  134. oi = parseFloat($(o1).attr('oi'));
  135. fa = this.fileallarr[oi];
  136. one= o.parent().find('font').html().replace('.'+fa.fileext+'','');
  137. if(get('confirm_main')){
  138. var nr = prompt('新文件名', one);
  139. if(nr){
  140. var newfie = nr+'.'+fa.fileext;
  141. o.parent().find('font').html(newfie);
  142. me.fileallarr[oi].filename=newfie;
  143. }
  144. }else{
  145. js.prompt('修改文件名','新文件名', function(jg,nr){
  146. if(jg=='yes' && nr){
  147. var newfie = nr+'.'+fa.fileext;
  148. o.parent().find('font').html(newfie);
  149. me.fileallarr[oi].filename=newfie;
  150. }
  151. }, one);
  152. }
  153. };
  154. this.compressimg=function(path,fobj,call){
  155. var img = new Image();
  156. img.src = path;
  157. if(!call)call=function(){};
  158. img.onload = function(){
  159. var that = this;
  160. var w = that.width,
  161. h = that.height,
  162. scale = w / h;
  163. var quality = me.quality;//压缩图片质量
  164. var canvas = document.createElement('canvas');
  165. var ctx = canvas.getContext('2d');
  166. var anw = document.createAttribute("width");
  167. anw.nodeValue = w;
  168. var anh = document.createAttribute("height");
  169. anh.nodeValue = h;
  170. canvas.setAttributeNode(anw);
  171. canvas.setAttributeNode(anh);
  172. ctx.drawImage(that, 0, 0, w, h);
  173. var base64 = canvas.toDataURL(fobj.type, quality);
  174. var nfobj = me.base64toblob(base64);
  175. call(nfobj);
  176. }
  177. };
  178. this.base64toblob=function(urlData){
  179. var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1],
  180. bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  181. while(n--){
  182. u8arr[n] = bstr.charCodeAt(n);
  183. }
  184. return new Blob([u8arr], {type:mime});
  185. };
  186. this.getimgview=function(o1){
  187. try{
  188. return URL.createObjectURL(o1.files.item(0));
  189. }catch(e){return false;}
  190. };
  191. this.isfields=function(a){
  192. var bo = false,i,d=this.fileallarr;
  193. for(i=0;i<d.length;i++){
  194. if(this.fileviewxu(d[i].xu) && d[i].filename==a.filename && d[i].filesize==a.filesize){
  195. return true;
  196. }
  197. }
  198. return bo;
  199. };
  200. this.sendbase64=function(nr,ocs){
  201. this.filearr=js.apply({filename:'截图.png',filesize:0,filesizecn:'',isimg:true,fileext:'png'}, ocs);
  202. this._startup(false, nr);
  203. };
  204. this.start=function(){
  205. return this.startss(0);
  206. };
  207. this.startss=function(oi){
  208. if(oi>=this.xu){
  209. var ids=''+this.oldids+'';
  210. var a = this.fileallarr;
  211. for(var i=0;i<a.length;i++)if(a[i].id)ids+=','+a[i].id+'';
  212. if(ids!='' && ids.substr(0,1)==',')ids=ids.substr(1);
  213. try{if(form(this.fileidinput))form(this.fileidinput).value=ids;}catch(e){};
  214. this.allsuccess(this.fileallarr, ids); //必须全部才触发
  215. return false;
  216. }
  217. this.nowoi = oi;
  218. var f=this.fileallarr[oi];
  219. if(!f || !this.fileviewxu(f.xu)){
  220. return this.startss(this.nowoi+1);
  221. }
  222. this.filearr = f;
  223. this.onsuccessa=function(f,str){
  224. var dst= js.decode(str);
  225. if(dst.id){
  226. this.fileallarr[this.nowoi].id=dst.id;
  227. this.fileallarr[this.nowoi].filepath=dst.filepath;
  228. }else{
  229. js.msg('msg', str);
  230. this.fileviewxu(this.nowoi, '<font color=red>失败1</font>');
  231. }
  232. this.startss(this.nowoi+1);
  233. }
  234. this.onprogressa=function(f,bil){
  235. this.fileviewxu(this.nowoi, ''+bil+'%');
  236. }
  237. this.onerror=function(){
  238. this.fileviewxu(this.nowoi, '<font color=red>失败0</font>');
  239. this.startss(this.nowoi+1);
  240. }
  241. this._startup(f.f);
  242. return true;
  243. };
  244. this.fileviewxu=function(oi,st){
  245. if(typeof(st)=='string')$('#'+this.fileview+'_'+oi+'').html(st);
  246. return get(''+this.fileview+'_'+oi+'');
  247. };
  248. //初始化文件防止重复上传
  249. this._initfile=function(f){
  250. var a = this.filearr,d={'filesize':a.filesize,'fileext':a.fileext};
  251. if(!a.isimg)d.filename=jm.base64encode(a.filename);
  252. var url = js.apiurl('upload','initfile', d);
  253. $.getJSON(url, function(ret){
  254. if(ret.success){
  255. var bstr = ret.data;
  256. me.upbool= false;
  257. me.onsuccess(a,bstr);
  258. }else{
  259. me._startup(f,false,true);
  260. }
  261. });
  262. };
  263. this._startup=function(fs, nr, bos){
  264. this.upbool = true;
  265. if(this.initpdbool && fs && !bos){this._initfile(fs);return;}
  266. try{var xhr = new XMLHttpRequest();}catch(e){js.msg('msg','当前浏览器不支持2');return;}
  267. this.urlparams.maxsize = this.maxsize;
  268. if(this.updir)this.urlparams.updir=this.updir;
  269. var url = this.upurl;
  270. if(!this.upurl)url = js.apiurl('upload','upfile', this.urlparams);
  271. xhr.open('POST', url, true);
  272. xhr.onreadystatechange = function(){me._statechange(this);};
  273. xhr.upload.addEventListener("progress", function(evt){me._onprogress(evt, this);}, false);
  274. xhr.addEventListener("load", function(){me._onsuccess(this);}, false);
  275. xhr.addEventListener("error", function(){me._error(false,this);}, false);
  276. if(nr)fs = this.base64toblob(nr);
  277. var fd = new FormData();
  278. fd.append('file', fs, this.filearr.filename);
  279. xhr.send(fd);
  280. this.xhr = xhr;
  281. this.upurl = '';
  282. };
  283. this.onsuccessa=function(){
  284. };
  285. this._onsuccess=function(o){
  286. this.upbool = false;
  287. var bstr = o.response;
  288. if(bstr.indexOf('id')<0 || o.status!=200){
  289. this._error(bstr);
  290. }else{
  291. this.onsuccessa(this.filearr,bstr,o);
  292. this.onsuccess(this.filearr,bstr,o);
  293. }
  294. };
  295. this._error=function(ts,xr){
  296. this.upbool = false;
  297. if(!ts)ts='上传内部错误';
  298. this.onerror(ts);
  299. };
  300. this._statechange=function(o){
  301. };
  302. this.onprogressa=function(){
  303. };
  304. this._onprogress=function(evt){
  305. var loaded = evt.loaded;
  306. var tot = evt.total;
  307. var per = Math.floor(100*loaded/tot);
  308. this.onprogressa(this.filearr,per, evt);
  309. this.onprogress(this.filearr,per, evt);
  310. };
  311. this.abort=function(){
  312. this.xhr.abort();
  313. this.upbool = false;
  314. this.onabort();
  315. };
  316. this._init();
  317. }
  318. $.rockupload = function(options){
  319. var cls = new rockupload(options,false);
  320. return cls;
  321. }
  322. })(jQuery);