欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2024-03-04 20:05:48
之前的移动端上传的方法,有些朋友测试说微信支持不是很好,还有部分安卓机也不支持,其实我已经有了另一个方法,但是例子还没整理出来,而联系我的很多朋友需要,所以就提前先发出来了...

之前的移动端上传的方法,有些朋友测试说微信支持不是很好,还有部分安卓机也不支持,其实我已经有了另一个方法,但是例子还没整理出来,而联系我的很多朋友需要,所以就提前先发出来了,并且做一个简单的说明,就不做一个demo了。

<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"> 
<title>图片压缩</title> 
<style> 
body { margin:0; padding:0; } 
html { font-size:62.5%; } 
 
.imgzip { padding:1em; } 
.imgzip .itm { padding-bottom:1em; word-break:break-all; font-size:1.2rem; line-height:1.5em; } 
.imgzip .itm .tit { margin-bottom:.5em; background-color:#e71446; color:#fff; padding:.5rem 1rem; border-radius:3px; } 
.imgzip .itm .cnt { padding:1rem; } 
.imgzip .itm .cnt img { display:block; max-width:100%; } 
.imgzip textarea { width:100%; height:20em; } 
</style> 
</head> 
 
<body> 
<script src="http://code.jquery.com/jquery-1.8.3.js"></script> 
<input type="file" accept="image/*;capture=camera" class="input"> 
<div class="imgzip"></div> 
<script> 
document.addeventlistener('domcontentloaded', init, false); 
 
function init() { 
var u = new uploadpic(); 
u.init({ 
input: document.queryselector('.input'), 
callback: function (base64) { 
$.ajax({ 
url:"{:u('upload')}", 
data:{str:base64,type:this.filetype}, 
type:'post', 
datatype:'json', 
success:function(i){ 
alert(i.info); 
} 
}) 
}, 
loading: function () { 
 
} 
}); 
} 
 
function uploadpic() { 
this.sw = 0; 
this.sh = 0; 
this.tw = 0; 
this.th = 0; 
this.scale = 0; 
this.maxwidth = 0; 
this.maxheight = 0; 
this.maxsize = 0; 
this.filesize = 0; 
this.filedate = null; 
this.filetype = ''; 
this.filename = ''; 
this.input = null; 
this.canvas = null; 
this.mime = {}; 
this.type = ''; 
this.callback = function () {}; 
this.loading = function () {}; 
} 
 
uploadpic.prototype.init = function (options) { 
this.maxwidth = options.maxwidth || 800; 
this.maxheight = options.maxheight || 600; 
this.maxsize = options.maxsize || 3 * 1024 * 1024; 
this.input = options.input; 
this.mime = {'png': 'image/png', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'bmp': 'image/bmp'}; 
this.callback = options.callback || function () {}; 
this.loading = options.loading || function () {}; 
 
this._addevent(); 
}; 
 
/** 
* @description 绑定事件 
* @param {object} elm 元素 
* @param {function} fn 绑定函数 
*/ 
uploadpic.prototype._addevent = function () { 
var _this = this; 
 
function tmpselectfile(ev) { 
_this._handelselectfile(ev); 
} 
 
this.input.addeventlistener('change', tmpselectfile, false); 
}; 
 
/** 
* @description 绑定事件 
* @param {object} elm 元素 
* @param {function} fn 绑定函数 
*/ 
uploadpic.prototype._handelselectfile = function (ev) { 
var file = ev.target.files[0]; 
 
this.type = file.type 
 
// 如果没有文件类型,则通过后缀名判断(解决微信及360浏览器无法获取图片类型问题) 
if (!this.type) { 
this.type = this.mime[file.name.match(/\.([^\.]+)$/i)[1]]; 
} 
 
if (!/image.(png|jpg|jpeg|bmp)/.test(this.type)) { 
alert('选择的文件类型不是图片'); 
return; 
} 
 
if (file.size > this.maxsize) { 
alert('选择文件大于' + this.maxsize / 1024 / 1024 + 'm,请重新选择'); 
return; 
} 
 
this.filename = file.name; 
this.filesize = file.size; 
this.filetype = this.type; 
this.filedate = file.lastmodifieddate; 
 
this._readimage(file); 
}; 
 
/** 
* @description 读取图片文件 
* @param {object} image 图片文件 
*/ 
uploadpic.prototype._readimage = function (file) { 
var _this = this; 
 
function tmpcreateimage(uri) { 
_this._createimage(uri); 
} 
 
this.loading(); 
 
this._geturi(file, tmpcreateimage); 
}; 
 
/** 
* @description 通过文件获得uri 
* @param {object} file 文件 
* @param {function} callback 回调函数,返回文件对应uri 
* return {bool} 返回false 
*/ 
uploadpic.prototype._geturi = function (file, callback) { 
var reader = new filereader(); 
var _this = this; 
 
function tmpload() { 
// 头不带图片格式,需填写格式 
var re = /^data:base64,/; 
var ret = this.result + ''; 
 
if (re.test(ret)) ret = ret.replace(re, 'data:' + _this.mime[_this.filetype] + ';base64,'); 
 
callback && callback(ret); 
} 
 
reader.onload = tmpload; 
 
reader.readasdataurl(file); 
 
return false; 
}; 
 
/** 
* @description 创建图片 
* @param {object} image 图片文件 
*/ 
uploadpic.prototype._createimage = function (uri) { 
var img = new image(); 
var _this = this; 
 
function tmpload() { 
_this._drawimage(this); 
} 
 
img.onload = tmpload; 
 
img.src = uri; 
}; 
 
/** 
* @description 创建canvas将图片画至其中,并获得压缩后的文件 
* @param {object} img 图片文件 
* @param {number} width 图片最大宽度 
* @param {number} height 图片最大高度 
* @param {function} callback 回调函数,参数为图片base64编码 
* return {object} 返回压缩后的图片 
*/ 
uploadpic.prototype._drawimage = function (img, callback) { 
this.sw = img.width; 
this.sh = img.height; 
this.tw = img.width; 
this.th = img.height; 
 
this.scale = (this.tw / this.th).tofixed(2); 
 
if (this.sw > this.maxwidth) { 
this.sw = this.maxwidth; 
this.sh = math.round(this.sw / this.scale); 
} 
 
if (this.sh > this.maxheight) { 
this.sh = this.maxheight; 
this.sw = math.round(this.sh * this.scale); 
} 
 
this.canvas = document.createelement('canvas'); 
var ctx = this.canvas.getcontext('2d'); 
 
this.canvas.width = this.sw; 
this.canvas.height = this.sh; 
 
ctx.drawimage(img, 0, 0, img.width, img.height, 0, 0, this.sw, this.sh); 
 
this.callback(this.canvas.todataurl(this.type)); 
 
ctx.clearrect(0, 0, this.tw, this.th); 
this.canvas.width = 0; 
this.canvas.height = 0; 
this.canvas = null; 
}; 
</script> 
</body> 
</html>

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

this.maxwidth = options.maxwidth || 800; 
this.maxheight = options.maxheight || 600; 
this.maxsize = options.maxsize || 3 * 1024 * 1024; 
this.input = options.input; 
this.mime = {'png': 'image/png', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'bmp': 'image/bmp'};

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

$.ajax({ 
url:"{:u('upload')}", 
data:{str:base64,type:this.filetype}, 
type:'post', 
datatype:'json', 
success:function(i){ 
alert(i.info); 
}

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

upload.php的内容

$str = $_post['str'];
    $type = $_post['type'];
 
    switch($type){
      case 'image/png':
        $ext='.png';
        break;
      case 'image/jpeg';
        $ext='.jpeg';
        break;
      case 'image/jpeg':
        $ext='.jpg';
        break;
      case 'image/bmp':
        $ext='.bmp';
        break;
      default:
        $ext='.jpg';
    }
    $file_path='./uploads/'.date('ymd').'/'.time().$ext;
    if(!file_exists(dirname($file_path))){
      mkdir(dirname($file_path),0777,true);
    }
    $img_content = str_replace('data:'.$type.';base64,','',$str);
    $img_content = base64_decode($img_content);
    $result =file_put_contents($file_path,$img_content);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。