1. 用 Canvas 生成图片

const getQrCode = () => {
    const drp = 2
    const width = 290.5 * drp
    const height = (width * 462) / 290.5
    const c = document.getElementById('myCanvas')
    const ctx = c.getContext('2d')
    ctx.fillStyle = '#fff'
    ctx.fillRect(0, 0, width, height)
    return c.toDataURL('image/jpeg')
}

2. 将 dataURL 转成 Blob

const dataURItoBlob = dataURI => {
    var byteString
    if (dataURI.split(',')[0].indexOf('base64') >= 0) byteString = atob(dataURI.split(',')[1])
    else byteString = unescape(dataURI.split(',')[1])
    var mimeString = dataURI
        .split(',')[0]
        .split(':')[1]
        .split(';')[0]
    var ia = new Uint8Array(byteString.length)
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i)
    }
    return new Blob([ia], { type: mimeString, name: '123.jpg' })
}

3. 上传到阿里云

const uploadBase = async files => {
    var oMyForm = new FormData()
    try {
        const name = files.name
        oMyForm.append('name', name)
        oMyForm.append('file', files)
        // 其他参数省略
        const { Status, message } = await api.fetch(apiUrl, oMyForm)
        if (Status === 'Ok') return Promise.resolve(url)
        return Promise.reject(message || '上传失败')
    } catch (error) {
        return Promise.reject(error.toString())
    }
}

4. 完整调用

(async () => {
    const dataUri = getQrCode()
	let url
    try {
        url = await uploadBase(dataURItoBlob(dataUri))
    } catch (error) {
        url = ''
    }
    console.log(url)
})()
发表评论
august
1111
monster
fffffffffffff
毅夏
en
毅夏
回复 @123123qwe: 不错!
毅夏
加油!
123123qwe
qwe
123123qwe
qqq
123123qwe
qqq
wsklxts
aaa
demo123456
demo123456