0

I am coding a webpage where the user can take a photo with his phone camera, then the image will be processed and stored in the server.

I am storing the image content on a <canvas> an showing it with <img> tag but I don't know how to send that information to the server.

A-fandino
  • 424
  • 5
  • 13

1 Answers1

0

I just solved it by converting the canvas content into a blob and sending it to the server with fetch:

Canvas to blob

someButton.onclick = (e) => {
   //some previous code
    canvas.toBlob(upload)
}

Upload Function

function upload(blob) {
    const form = new FormData();
    form.append("img_name",blob)
    fetch("/path/to/api", {
        method:'POST',
        body:form,
    }, ).then(res => res.text()).then(resp => console.log(resp))
}

Then the server treats the file as needed.

A-fandino
  • 424
  • 5
  • 13
  • Are you sure that the server will handle the blob object? I would convert it to a File object before sending it to the server. See [How to convert Blob to File in JavaScript](https://stackoverflow.com/a/31663645/387194). – jcubic Nov 11 '21 at 09:28
  • 1
    In my case it works perfectly fine. I'm using PHP and it gets included in the $_FILES array – A-fandino Nov 11 '21 at 09:49