【发布时间】: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
})
[...]
}
但是,如果不是直接上传图片,我想先裁剪它。所以我:
- 我首先将文件(使用 React)保存在本地状态,
- 裁剪它,
- 然后上传。
但是,这个过程似乎只适用于台式机/笔记本电脑,而不适用于移动设备。对于移动端,生成一个空图像,错误为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