PhoneGap中文网

 找回密码
 立即注册
查看: 76244|回复: 2
打印 上一主题 下一主题

移动端html5图片上传方法【更好的兼容安卓IOS和微信】

[复制链接]

493

主题

2035

帖子

6894

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
6894
跳转到指定楼层
楼主
发表于 2014-10-2 12:14:41 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
之前的移动端上传的方法,有些朋友测试说微信支持不是很好,还有部分安卓机也不支持,其实我已经有了另一个方法,但是例子还没整理出来,而联系我的很多朋友需要,所以就提前先发出来了,并且做一个简单的说明,就不做一个demo了。

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
  6. <title>图片压缩</title>
  7. <style>
  8. body { margin:0; padding:0; }
  9. html { font-size:62.5%; }

  10. .imgzip { padding:1em; }
  11. .imgzip .itm { padding-bottom:1em; word-break:break-all; font-size:1.2rem; line-height:1.5em; }
  12. .imgzip .itm .tit { margin-bottom:.5em; background-color:#e71446; color:#FFF; padding:.5rem 1rem; border-radius:3px; }
  13. .imgzip .itm .cnt { padding:1rem; }
  14. .imgzip .itm .cnt img { display:block; max-width:100%; }
  15. .imgzip textarea { width:100%; height:20em; }
  16. </style>
  17. </head>

  18. <body>
  19. <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
  20. <input type="file" accept="image/*;capture=camera" class="input">
  21. <div class="imgzip"></div>
  22. <script>
  23. document.addEventListener('DOMContentLoaded', init, false);

  24. function init() {
  25. var u = new UploadPic();
  26. u.init({
  27. input: document.querySelector('.input'),
  28. callback: function (base64) {
  29. $.ajax({
  30. url:"{:U('upload')}",
  31. data:{str:base64,type:this.fileType},
  32. type:'post',
  33. dataType:'json',
  34. success:function(i){
  35. alert(i.info);
  36. }
  37. })
  38. },
  39. loading: function () {

  40. }
  41. });
  42. }

  43. function UploadPic() {
  44. this.sw = 0;
  45. this.sh = 0;
  46. this.tw = 0;
  47. this.th = 0;
  48. this.scale = 0;
  49. this.maxWidth = 0;
  50. this.maxHeight = 0;
  51. this.maxSize = 0;
  52. this.fileSize = 0;
  53. this.fileDate = null;
  54. this.fileType = '';
  55. this.fileName = '';
  56. this.input = null;
  57. this.canvas = null;
  58. this.mime = {};
  59. this.type = '';
  60. this.callback = function () {};
  61. this.loading = function () {};
  62. }

  63. UploadPic.prototype.init = function (options) {
  64. this.maxWidth = options.maxWidth || 800;
  65. this.maxHeight = options.maxHeight || 600;
  66. this.maxSize = options.maxSize || 3 * 1024 * 1024;
  67. this.input = options.input;
  68. this.mime = {'png': 'image/png', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'bmp': 'image/bmp'};
  69. this.callback = options.callback || function () {};
  70. this.loading = options.loading || function () {};

  71. this._addEvent();
  72. };

  73. /**
  74. * @description 绑定事件
  75. * @param {Object} elm 元素
  76. * @param {Function} fn 绑定函数
  77. */
  78. UploadPic.prototype._addEvent = function () {
  79. var _this = this;

  80. function tmpSelectFile(ev) {
  81. _this._handelSelectFile(ev);
  82. }

  83. this.input.addEventListener('change', tmpSelectFile, false);
  84. };

  85. /**
  86. * @description 绑定事件
  87. * @param {Object} elm 元素
  88. * @param {Function} fn 绑定函数
  89. */
  90. UploadPic.prototype._handelSelectFile = function (ev) {
  91. var file = ev.target.files[0];

  92. this.type = file.type

  93. // 如果没有文件类型,则通过后缀名判断(解决微信及360浏览器无法获取图片类型问题)
  94. if (!this.type) {
  95. this.type = this.mime[file.name.match(/\.([^\.]+)$/i)[1]];
  96. }

  97. if (!/image.(png|jpg|jpeg|bmp)/.test(this.type)) {
  98. alert('选择的文件类型不是图片');
  99. return;
  100. }

  101. if (file.size > this.maxSize) {
  102. alert('选择文件大于' + this.maxSize / 1024 / 1024 + 'M,请重新选择');
  103. return;
  104. }

  105. this.fileName = file.name;
  106. this.fileSize = file.size;
  107. this.fileType = this.type;
  108. this.fileDate = file.lastModifiedDate;

  109. this._readImage(file);
  110. };

  111. /**
  112. * @description 读取图片文件
  113. * @param {Object} image 图片文件
  114. */
  115. UploadPic.prototype._readImage = function (file) {
  116. var _this = this;

  117. function tmpCreateImage(uri) {
  118. _this._createImage(uri);
  119. }

  120. this.loading();

  121. this._getURI(file, tmpCreateImage);
  122. };

  123. /**
  124. * @description 通过文件获得URI
  125. * @param {Object} file 文件
  126. * @param {Function} callback 回调函数,返回文件对应URI
  127. * return {Bool} 返回false
  128. */
  129. UploadPic.prototype._getURI = function (file, callback) {
  130. var reader = new FileReader();
  131. var _this = this;

  132. function tmpLoad() {
  133. // 头不带图片格式,需填写格式
  134. var re = /^data:base64,/;
  135. var ret = this.result + '';

  136. if (re.test(ret)) ret = ret.replace(re, 'data:' + _this.mime[_this.fileType] + ';base64,');

  137. callback && callback(ret);
  138. }

  139. reader.onload = tmpLoad;

  140. reader.readAsDataURL(file);

  141. return false;
  142. };

  143. /**
  144. * @description 创建图片
  145. * @param {Object} image 图片文件
  146. */
  147. UploadPic.prototype._createImage = function (uri) {
  148. var img = new Image();
  149. var _this = this;

  150. function tmpLoad() {
  151. _this._drawImage(this);
  152. }

  153. img.onload = tmpLoad;

  154. img.src = uri;
  155. };

  156. /**
  157. * @description 创建Canvas将图片画至其中,并获得压缩后的文件
  158. * @param {Object} img 图片文件
  159. * @param {Number} width 图片最大宽度
  160. * @param {Number} height 图片最大高度
  161. * @param {Function} callback 回调函数,参数为图片base64编码
  162. * return {Object} 返回压缩后的图片
  163. */
  164. UploadPic.prototype._drawImage = function (img, callback) {
  165. this.sw = img.width;
  166. this.sh = img.height;
  167. this.tw = img.width;
  168. this.th = img.height;

  169. this.scale = (this.tw / this.th).toFixed(2);

  170. if (this.sw > this.maxWidth) {
  171. this.sw = this.maxWidth;
  172. this.sh = Math.round(this.sw / this.scale);
  173. }

  174. if (this.sh > this.maxHeight) {
  175. this.sh = this.maxHeight;
  176. this.sw = Math.round(this.sh * this.scale);
  177. }

  178. this.canvas = document.createElement('canvas');
  179. var ctx = this.canvas.getContext('2d');

  180. this.canvas.width = this.sw;
  181. this.canvas.height = this.sh;

  182. ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, this.sw, this.sh);

  183. this.callback(this.canvas.toDataURL(this.type));

  184. ctx.clearRect(0, 0, this.tw, this.th);
  185. this.canvas.width = 0;
  186. this.canvas.height = 0;
  187. this.canvas = null;
  188. };
  189. </script>
  190. </body>
  191. </html>
复制代码

这个也是把图片转成了base64去传送,个人不建议去用js改变图片的大小,建议裁切缩放还是PHP来做吧。

  1. this.maxWidth = options.maxWidth || 800;
  2. this.maxHeight = options.maxHeight || 600;
  3. this.maxSize = options.maxSize || 3 * 1024 * 1024;
  4. this.input = options.input;
  5. this.mime = {'png': 'image/png', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'bmp': 'image/bmp'};
复制代码

这一部分是对上传图片的配置,应该可以看懂,可以自己去改

  1. $.ajax({
  2. url:"{:U('upload')}",
  3. data:{str:base64,type:this.fileType},
  4. type:'post',
  5. dataType:'json',
  6. success:function(i){
  7. alert(i.info);
  8. }
复制代码



这部分是上传以后ajax发送base64码到php,
base64码带有图片的说明字符串,所以得用正则去掉,然后base64解码保存到图片的文件中。并且返回地址即可



原文来自:http://a3147972.blog.51cto.com/2366547/1554698


回复

使用道具 举报

7

主题

27

帖子

110

积分

注册会员

Rank: 2

积分
110
沙发
发表于 2015-1-21 12:07:29 | 只看该作者
要是有demo就好了
回复 支持 反对

使用道具 举报

0

主题

1

帖子

4

积分

新手上路

Rank: 1

积分
4
板凳
发表于 2015-3-11 13:49:15 | 只看该作者
手机端上传图片EXIF信息会丢失,不知道怎么回事,同样的代码PC端上传就没问题
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

站长推荐 上一条 /1 下一条

ionic4视频教程

Archiver|手机版|小黑屋| PhoneGap中文网 ( 京ICP备13027796号-1 )  

GMT+8, 2024-6-27 00:33 , Processed in 0.046284 second(s), 36 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表