Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

一键上传canvas所生成的图片至CDN #10

Open
spiritree opened this issue Dec 2, 2018 · 0 comments
Open

一键上传canvas所生成的图片至CDN #10

spiritree opened this issue Dec 2, 2018 · 0 comments

Comments

@spiritree
Copy link
Owner

本文链接:https://deeptree.me/post/2018/07/uploadcanvasimg/
简介:�分析如何通过canvas生成图片并上传至CDN

起因

最近在做动态生成海报的项目,有生成海报后上传当前canvas图片的需求。

分析

脑袋一拍,思索出流程是这样canvas=>base64=>POST接口。但是常见的CDN不支持base64啊!查了下发现有canvas.toBlob(兼容性为Chrome50+)

于是流程改为canvas=>blob=>POST接口,但发现CDN还是不吃这一套,接口报错

思来想去,决定用普通的手动上传方式<input type="file" />看下请求格式(如图)

imgpost

Content-Type可以看出需要使用FormData对象去上传

红框部分则是<input type="file" />所生成的

分析一通后,梳理流程为canvas=>blob=>File=>FormData=>POST

代码

upload = () => {
  return new Promise((resolve, reject) => {
    canvasInstance.toBlob(blob => {
      // blob转file
      const file = new File([blob], 'poster.png', {
        type: 'image/png',
        lastModified: Date.now()
      })
      const xhr = new XMLHttpRequest()
      xhr.onreadystatechange = () => {
        try {
          if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 400) {
            const res = JSON.parse(xhr.responseText)
            resolve(res)
          }
        } catch {
          reject(new Error(xhr.statusText))
        }
      }
      xhr.open(
        'POST',
        `${cdnUrl}`,
        true
      )
      // 转换成通过input上传的文件
      let formData = new FormData()
      formData.append('file', file)
      xhr.send(formData)
    }, 'image/png')
  })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant