【问题标题】:Upload file (HTML5 canvas image → file) in javascript在javascript中上传文件(HTML5画布图像→文件)
【发布时间】:2017-12-18 17:42:30
【问题描述】:

尝试按照以下说明将图像作为文件上传:https://github.com/graphcool-examples/react-graphql/blob/master/files-with-apollo/src/components/CreatePage.js#L48-L65

上述说明适用于移动设备和台式机/笔记本电脑:

handleDrop(files) {
  let data = new FormData()
  data.append('data', person.avatar)
  fetch('https://api.graph.cool/file/v1/___PROJECTID___', {
    method: 'POST',
    body: data
  })
  [...]
}

但是,如果不是直接上传图片,我想先裁剪它。所以我:

  1. 我首先将文件(使用 React)保存在本地状态,
  2. 裁剪它,
  3. 然后上传。

但是,这个过程似乎只适用于台式机/笔记本电脑,而不适用于移动设备。对于移动端,生成一个空图像,错误为InvalidStateError (DOM Exception 11): The object is in an invalid state.

我想知道这是否与移动设备的文件存储限制有关。一个潜在的解决方案可能是使用FileReader

以下代码适用于台式机/笔记本电脑,但不适用于移动设备:

handleDrop(files) {
  // First save file to local state
  this.setState({ file: file[0] })
}

// Image is then cropped, upon which handleCrop() is called

handleCrop() {
  // This returns a HTMLCanvasElement, it can be made into a data URL or a blob, drawn on another canvas, or added to the DOM.
  const image = this.refs.avatar.getImageScaledToCanvas().toDataURL()
  // Custom DataURLtoBlob() function
  const blob = DataURLtoBlob(image)
  let file = new File([blob], 'avatar.png', {
    lastModified: new Date(),
    type: "image/png"
  })
  let data = new FormData()
  data.append('data', file)
  fetch('https://api.graph.cool/file/v1/___PROJECTID___', {
    method: 'POST',
    body: data
  })
  [...]
}

【问题讨论】:

    标签: javascript file reactjs blob filereader


    【解决方案1】:

    找到了解决办法。不要将blob 转换回File。相反,只需上传blob ?

    handleDrop(files) {
      // First save file to local state
      this.setState({ file: file[0] })
    }
    
    // Image is then cropped, upon which handleCrop() is called
    
    handleCrop() {
      // This returns a HTMLCanvasElement, it can be made into a data URL or a blob, drawn on another canvas, or added to the DOM.
      const image = this.refs.avatar.getImageScaledToCanvas().toDataURL()
      // Custom DataURLtoBlob() function
      const blob = DataURLtoBlob(image)
      let data = new FormData()
      data.append('data', blob)
      fetch('https://api.graph.cool/file/v1/___PROJECTID___', {
        method: 'POST',
        body: data
      })
      [...]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-10
      • 2018-06-12
      • 1970-01-01
      • 2012-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多