Search code examples
javascriptarraysxmlhttprequestfetch

JavaScript - send image to server as binary data


I have an Image object

   var ctx = canvas.getContext('2d');
   ctx.drawImage(imageBitmap, 0, 0);
   var imgData=ctx.getImageData(0,0,W,H);

How can I now pass imgData as binary data (or a string) to the server using POST method?


Solution

  • First, you must get byte array of the image. It's easy:

    let bytes = imgData.data
    

    Then, send bytes to server. It's simple too:

    fetch('https://example.net/',{method: 'POST', body: bytes}).then((res) => ...)
    

    But, as a matter of fact, their is very few server which receive raw image data. In reality, send processed data such as jpeg compression and base64 encoding.