上传文件(HTML5画布图像→文件)以JavaScript
问题描述:
试图上传图片按照这些指令的文件:https://github.com/graphcool-examples/react-graphql/blob/master/files-with-apollo/src/components/CreatePage.js#L48-L65上传文件(HTML5画布图像→文件)以JavaScript
上述引用的指令在移动设备和桌面/笔记本电脑上工作:
handleDrop(files) {
let data = new FormData()
data.append('data', person.avatar)
fetch('https://api.graph.cool/file/v1/___PROJECTID___', {
method: 'POST',
body: data
})
[...]
}
但是,如果不是直接上传图片,我想先裁剪它。所以我:
- 我(使用反应)的文件保存在本地状态第一,
- 裁剪,
- 然后上传。
但是,这个过程似乎只适用于台式机/笔记本电脑,但不适用于手机。对于手机,产生一个空的图像,错误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
})
[...]
}
答
找到了解决办法。不要将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
})
[...]
}