2017-07-13 71 views
1

試圖上傳圖片按照這些指令的文件: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 
    }) 
    [...] 
} 

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

  1. 我(使用反應)的文件保存在本地狀態第一,
  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 
    }) 
    [...] 
} 

回答

0

找到了解決辦法。不要將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 
    }) 
    [...] 
}