Uploading a canvas image to facebook as Blob of multipart/form-data type

后端 未结 2 610
死守一世寂寞
死守一世寂寞 2021-01-05 14:31

I am trying to use the facebook api to upload an image from a canvas I save on the page:

var file = dataURItoBlob(canvas.toDataURL(\'image/jpeg\', 1.0))

FB.         


        
2条回答
  •  臣服心动
    2021-01-05 15:03

    I figured out, for some reason, the issues was the headers that I tried to apply as a solution for a previous problem... Here is a working solution: https://jsfiddle.net/ilyador/vyne7oh2/8/

    function fbUpload(token){
      var dataURL = canvas.toDataURL('image/jpeg', 1.0)
      var blob = dataURItoBlob(dataURL)
      var formData = new FormData()
      formData.append('token', token)
      formData.append('source', blob)
    
      var xhr = new XMLHttpRequest();
      xhr.open( 'POST', 'https://graph.facebook.com/me/photos', true )
      xhr.onload = xhr.onerror = function() {
        console.log( xhr.responseText )
      };
      xhr.send( formData )
    }
    
    function dataURItoBlob(dataURI) {
      var byteString = atob(dataURI.split(',')[1]);
      var ab = new ArrayBuffer(byteString.length);
      var ia = new Uint8Array(ab);
      for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); }
      return new Blob([ab], { type: 'image/jpeg' });
    }
    

提交回复
热议问题