TPMupload.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. //兼容phonegap,电脑,手机的上传插件
  2. //autor luofei614(http://weibo.com/luofei614)
  3. ;(function($){
  4. $.fn.extend({
  5. TPMupload:function(options){
  6. //配置项处理
  7. var defaults={
  8. "url":"",
  9. "name":"file",
  10. "sourceType":"Image", //针对手机有效, 上传类型,Image,Video,Audio,Libray 注意首字母大写。 Libray 表示上传手机相册中的图片。
  11. "dataUrl":true,
  12. "quality":20,//图片质量
  13. "imgWidth":300,
  14. "imgHeight":300
  15. };
  16. if('string'==$.type(options))
  17. options={"url":options};
  18. var op=$.extend(defaults,options);
  19. //电脑上传
  20. var desktop_upload=function(index){
  21. op.name=$(this).attr('name') || op.name
  22. //增加上传按钮
  23. var $uploadBtn=$('<input type="button" class="TPMupload_btn" value="上传" />').insertBefore(this);
  24. //添加状态层
  25. var $status=$('<span class="TPMupload_status"></span>').insertBefore(this);
  26. //增加隐藏域
  27. var $hiddenInput=$('<input type="hidden" name="'+op.name+'" value="" />').insertBefore(this);;
  28. //增加结果显示层
  29. var $show=$('<div class="TPMupload_show"></div>').insertBefore(this);
  30. //增加提交表单
  31. var $form=$('<form action="'+op.url+'" target="TPMupload_iframe_'+index+'" method="post" enctype="multipart/form-data"> <input type="file" size="1" name="'+op.name+'" style="cursor:pointer;" /> </form>').css({"position":"absolute","opacity":"0"}).insertBefore(this);
  32. //定位提交表单
  33. $uploadBtn.hover(function(e){
  34. $form.offset({top:e.pageY-20,left:e.pageX-50});
  35. });
  36. var $uploadInput=$form.find('input:file');
  37. $uploadInput.change(function(){
  38. $status.html('正在上传...');
  39. $form.submit();
  40. });
  41. $(this).remove();
  42. //增加iframe
  43. var $iframe=$('<iframe id="TPMupload_iframe_'+index+'" name="TPMupload_iframe_'+index+'" style="display:none" src="about:blank"></iframe>').appendTo('body');
  44. //获得iframe返回结果
  45. var iframe=$iframe[0];
  46. $iframe.bind("load", function(){
  47. if (iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" || // For Safari
  48. iframe.src == "javascript:'<html></html>';") { // For FF, IE
  49. return;
  50. }
  51. var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document;
  52. // fixing Opera 9.26,10.00
  53. if (doc.readyState && doc.readyState != 'complete') return;
  54. // fixing Opera 9.64
  55. if (doc.body && doc.body.innerHTML == "false") return;
  56. var response;
  57. if (doc.XMLDocument) {
  58. // response is a xml document Internet Explorer property
  59. response = doc.XMLDocument;
  60. } else if (doc.body){
  61. try{
  62. response = $iframe.contents().find("body").html();
  63. } catch (e){ // response is html document or plain text
  64. response = doc.body.innerHTML;
  65. }
  66. } else {
  67. // response is a xml document
  68. response = doc;
  69. }
  70. if(''!=response){
  71. $status.html('');
  72. if(-1!=response.indexOf('<pre>')){
  73. //iframe中的json格式,浏览器会自动渲染,加上pre标签,转义html标签,所以这里去掉pre标签,还原html标签。
  74. var htmldecode=function(str)
  75. {
  76. var s = "";
  77. if (str.length == 0) return "";
  78. s = str.replace(/&amp;/g, "&");
  79. s = s.replace(/&lt;/g,"<");
  80. s = s.replace(/&gt;/g,">");
  81. s = s.replace(/&nbsp;/g," ");
  82. s = s.replace(/'/g,"\'");
  83. s = s.replace(/&quot;/g, "\"");
  84. s = s.replace(/<br>/g,"\n");
  85. return s;
  86. }
  87. response=htmldecode($(response).html());
  88. console.log(response);
  89. }
  90. try{
  91. var ret=$.parseJSON(response);
  92. //显示图片
  93. if(ret.path) $hiddenInput.val(ret.path);
  94. if(ret.show) $show.html(ret.show);
  95. if(ret.error) $show.html(ret.error);
  96. }catch(e){
  97. console.log(response);
  98. alert('服务器返回格式错误');
  99. }
  100. }
  101. });
  102. };
  103. //客户端上传
  104. var client_upload=function(index){
  105. op.name=$(this).attr('name') || op.name
  106. //增加上传按钮
  107. var $uploadBtn=$('<input type="button" class="TPMupload_btn" value="上传" />').insertBefore(this);
  108. //添加状态层
  109. var $status=$('<span class="TPMupload_status"></span>').insertBefore(this);
  110. //增加隐藏域
  111. var $hiddenInput=$('<input type="hidden" name="'+op.name+'" value="" />').insertBefore(this);;
  112. //增加结果显示层
  113. var $show=$('<div class="TPMupload_show"></div>').insertBefore(this);
  114. $(this).remove();
  115. var upload=function(file,isbase64){
  116. isbase64=isbase64 || false;
  117. if('http'!=op.url.substr(0,4).toLowerCase()){
  118. //如果上传地址不是绝对地址, 加上TPM的基路径。
  119. op.url=TPM.op.api_base+op.url;
  120. }
  121. if(isbase64){
  122. //如果是base64的图片数据
  123. var $imgshow=$('<div><img src="data:image/png;base64,'+file+'" /><br /><span>点击图片可调整图片角度</span></div>').appendTo($show);
  124. var $img=$imgshow.find('img');
  125. $imgshow.click(function(){
  126. var c=document.createElement('canvas');
  127. var ctx=c.getContext("2d");
  128. var img=new Image();
  129. img.onload = function(){
  130. c.width=this.height;
  131. c.height=this.width;
  132. ctx.rotate(90 * Math.PI / 180);
  133. ctx.drawImage(img, 0,-this.height);
  134. var dataURL = c.toDataURL("image/png");
  135. $img.attr('src',dataURL);
  136. $hiddenInput.val(dataURL);
  137. };
  138. img.src=$img.attr('src');
  139. });
  140. $hiddenInput.val('data:image/png;base64,'+file);
  141. }else{
  142. $status.html('正在上传...');
  143. //视频,语音等文件上传
  144. resolveLocalFileSystemURI(file,function(fileEntry){
  145. fileEntry.file(function(info){
  146. var options = new FileUploadOptions();
  147. options.fileKey=op.name;
  148. options.chunkedMode=false;
  149. var ft = new FileTransfer();
  150. ft.upload(info.fullPath,op.url,function(r){
  151. $status.html('');
  152. try{
  153. var ret=$.parseJSON(r.response);
  154. //显示图片
  155. if(ret.path) $hiddenInput.val(ret.path);
  156. if(ret.show) $show.html(ret.show);
  157. if(ret.error) $show.html(ret.error);
  158. }catch(e){
  159. console.log(r.response);
  160. alert('服务器返回格式错误');
  161. }
  162. },function(error){
  163. $status.html('');
  164. alert("文件上传失败,错误码: " + error.code);
  165. },options);
  166. });
  167. });
  168. }
  169. };
  170. //扑捉对象
  171. $uploadBtn.click(function(){
  172. if('Libray'==op.sourceType || 'Image'==op.sourceType){
  173. var sourceType='Image'==op.sourceType?navigator.camera.PictureSourceType.CAMERA:navigator.camera.PictureSourceType.PHOTOLIBRARY;
  174. var destinationType=op.dataUrl?navigator.camera.DestinationType.DATA_URL:navigator.camera.DestinationType.FILE_URI;
  175. navigator.camera.getPicture(function(imageURI){
  176. upload(imageURI,op.dataUrl);
  177. }, function(){
  178. }, {quality:op.quality,destinationType: destinationType,sourceType:sourceType,targetWidth:op.imgWidth,targetHeight:op.imgHeight});
  179. }else{
  180. var action='capture'+op.sourceType;
  181. navigator.device.capture[action](function(mediaFiles){
  182. upload(mediaFiles[0].fullPath);
  183. },function(){
  184. });
  185. }
  186. });
  187. };
  188. $(this).each(function(index){
  189. //在SAE云窗调试器下可能有延迟问题,第一次加载会判断window.cordova未定义,这时候需要点击一下页面其他链接,再点击回来就可以了
  190. if('cordova' in window){
  191. //手机上的处理方法
  192. client_upload.call(this,index);
  193. }else{
  194. //电脑上的处理方法
  195. desktop_upload.call(this,index);
  196. }
  197. });
  198. }
  199. });
  200. })(jQuery);