Search code examples
javascriptcanvasjpeg

Send the image created on canvas to the backend server


I have canvas and for now, i downloaded jpg file with this.

 var a = document.createElement('a');
 a.href = ref_canvas_release.current.toDataURL('image/jpeg', 0.85);
 
 a.download = GlobalParam.fileObj.project_name + '.jpg';
 a.click();

then now I want to upload this image to backend instead of download.

So, what I want to do is like this,

    fileimage = ref_canvas_release.current.toDataURL('image/jpeg', 0.85);
    const formData = new FormData();

    //It's not correct.
    formData.append("myfile",fileimage);
    
    var url = '/get_thumbnail';
    axios.post(url, formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }).then((res) =>{
        console.log(res);
    });

maybe I don't need to make file but use bytestream,

However how can I do this?


Solution

  • For that you will need to use toBlob method, so we can create a new image file from blob easily.

    ref_canvas_release.current.toBlob((blob) => {
           
            const file = new File([blob], "canvas.jpeg",{type:"image/jpeg"});
    
            const formData = new FormData();
    
            formData.append('myfile', file);
    
            let url = '/get_thumbnail';
            axios
                .post(url, formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                })
                .then(res => {
                    console.log(res);
                });
        },
        'image/jpeg',
        0.85
    );
    

    MDN Docs