首页 微信js-sdk选择图片并上传到oss
文章
取消

微信js-sdk选择图片并上传到oss

1、引入微信/企业微信js-sdk

微信环境下,需要自己引入微信sdk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport"
    content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
  <link rel="icon" href="/favicon.png">
  <title>图片上传</title>
  <script src="//res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
</head>

<body>
  <div id="app"></div>
</body>

</html>

2、安装oss-sdk、uuid

1
2
3
4
5
// cnpm i ali-oss uuid -S
// 引入OSS、uuid

import OSS from 'ali-oss';
import { v4asuuidv4 } from'uuid'

3、调用chooseImage选择图库中的图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
export const chooseImg = (count = 3) => {
  return new Promise(resolve => {
    window.wx.chooseImage({
      count,
      sizeType: ['original'],
      sourceType: ['album'],
      success: async function (res) {
        // res.localIds 获取到选中图片ids
        if (!res.localIds.length) {
          return
        }
        const imgList = []
        for (const item of res.localIds) {
          // 获取到图片的base64
          const imgStr = await getImgBase64(item)
          // 上传到oss,并返回oss地址
          const url = await uploadImg(imgStr)
          imgList.push(url)
        }
        resolve(imgList)
      }
    })
  })
}

4、调用js-sdk的getLocalImgData API,根据Id获取到图片的base64字符串

1
2
3
4
5
6
7
8
9
10
const getImgBase64 = (id) => {
  return new Promise((resolve) => {
    window.wx.getLocalImgData({
      localId: id,
      success: function (res) {
        resolve(res.localData)
      }
    })
  })
}

5、将base64转为文件,并上传到oss

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const base64ToBlob = (urlData, type) => {
  const arr = urlData.split(',')
  const mime = arr[0].match(/:(.*?);/)[1] || type
  const bytes = window.atob(arr[1])
  const ab = new ArrayBuffer(bytes.length)
  const ia = new Uint8Array(ab)
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i)
  }
  return new Blob([ab], {
    type: mime
  })
}

const uploadImg = async (file) => {
  const id = uuidv4()
  const fileData = base64ToBlob(file, 'image/png')
  const client = new OSS({
        // yourRegion填写Bucket所在地域。以华东1(杭州)为例,yourRegion填写为oss-cn-hangzhou。
        region: 'yourRegion',
        // 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
        accessKeyId: 'yourAccessKeyId',
        accessKeySecret: 'yourAccessKeySecret',
        // 从STS服务获取的安全令牌(SecurityToken)。
        stsToken: 'yourSecurityToken',
        // 填写Bucket名称。
        bucket: 'examplebucket'
      });

  try {
    const uploadRes = await client.put(`/xxx/${id}`, fileData) // xxx 替换为自己的oss路径
    if (!uploadRes.url) {
      throw new Error('上传失败')
    }
    return uploadRes.url
  } catch (e) {
    console.error('error: %j', e)
    return ''
  }
}
本文由作者按照 CC BY 4.0 进行授权