h5上传图片

最近遇到一个需求,要求手机拍照上传图片或选择相册图片上传,记录一下实现方式。

<input type="file">

可以调用拍照和上传图片的接口,测试了一下ios和android,发现在安卓手机的微信浏览器,只能选择图片,无法拍照,于是决定微信浏览器使用微信开放平台的接口,其他浏览器直接使用input。

一、使用input type=file 上传

html中写<input type="file" accept="image/*"/> accept=”image/*表示只选择图片格式的文件。js中给input绑定change事件

使用h5的FileReader对象,读取图片文件转成base64,为了避免传上去的文件太大,用canvas压缩图片。canvas.toDataURL('image/jpeg', 0.1)前一个参数是图片格式,后一个参数是图片的质量,范围是0.1~1.预览图片可直接将base64编码放到img标签的src中。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$('input[type="file"]').on('change',function(evt){
var file = evt.target.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e) {
var img = new Image();
img.src = e.target.result;
img.onload = function(){
var canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var compressBase64 = canvas.toDataURL('image/jpeg', 0.1);
}
}
});

二、微信中使用微信的上传图片接口
引用微信的API

1
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js" type="text/javascript"></script>
wx.config({
    debug: false,
    appId: weixinConfigInfo['appId'],
    timestamp: weixinConfigInfo['timestamp'],
    nonceStr: weixinConfigInfo['nonceStr'],
    signature: weixinConfigInfo['signature'],
    jsApiList: [
      "onMenuShareTimeline",
        "onMenuShareAppMessage",
       "onMenuShareQQ",
      "onMenuShareWeibo",
      "chooseImage",
      "uploadImage"
        ]
  });
  var images = {
  localId:[],
  serverId:[]
};
wx.chooseImage({
    //count: 1, // 默认9
    //sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
    success: function(res) {
      // alert(res.localIds);
      images.localId = res.localIds;
      if (images.localId.length === 0) {
        alert('请先使用 chooseImage 接口选择图片');
        return;
      }
      if (images.localId.length > 1) {
        alert('目前仅支持单张图片上传,请重新上传');
        images.localId = [];
        return;
      }
      var i = 0,length = images.localId.length;
      images.serverId = [];
         wx.uploadImage({
              localId: images.localId[0],
              success: function(res) {
              //res.serverId是微信服务器返回的id,需要去微信服务器将图片下载下来,详见微信api
              },
              fail: function(res) {
                alert('上传失败!');
              }
            });
    }
  });