Oscar Gonzalez
Oscar Gonzalez

Reputation: 138

How to use an image generated in Javascript in a function inside my Django's view?

I'm making an application where my view renders a template with information, then inside my template with Javascript I create a canvas element, I have the data:URI in my Javascript code, but I want to save correctly that image in my MEDIA_ROOT (supposed in /media/report directory) on my server in a Django's way, as I do in another view with a form, but this is not a form! Is a success page where render the template with information and in the same view I have a function that I need that image, maybe my problem can be a little tricky but I will put my template code and my view code to show what I want to do. I don't know if I'm thinking correctly. I really don't need to save that image, just need to use in the function do_something_with_image()

def success(request, report_id):
    data1 = data2 = ''

    try:
        report = Report.objects.get(id=report_id)

        data1= report.data1
        data2= report.data2

        #picture_path is /media/report/report_id.png or the file generated in Javascript
        do_something_with_image(picture_path)
        
    except:
        messages.error(request, "Error")

    context={
        'report_id': report_id,
        'data1': data1,
        'data2': data2,
    }

    return render(request, 'exito.html', context) 

Maybe I need to do a POST request?

Here is my template code with the javascript code:

        <div id="report">
          {{data1}} info - info {{data2}}
        </div>
        <script>
        
        window.onload = function() {
            //dom not only ready, but everything is loaded
            html2canvas(document.getElementById("report")).then(canvas => {
                let image = canvas.toDataURL("image/png").replace("image/png","image/octet-stream");
                let link = document.getElementById('link');
                link.setAttribute('download', 'imageIWantToUse.png');
                link.setAttribute('href',image)
            });
        };
       </script>

Upvotes: 0

Views: 189

Answers (1)

kyle
kyle

Reputation: 2638

You will need to post the contents of the canvas to your server and then handle the request server side and save the file. First you need to get the canvas data, you should use toBlob for this. Once you have it, uou can use FormData and then POST that using the browsers fetch method. This would look like:

window.onload = () => {
  const report = document.getElementById("report");
  html2canvas(report).then((canvas) => {
    // toBlob -- https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob
    return canvas.toBlob((blob) => {
      // FormData -- https://developer.mozilla.org/en-US/docs/Web/API/FormData
      const form = new FormData();
      form.append("report", blob);

      fetch("YOUR SERVER URL", {
        method: "POST",
        body: form
      })
        .then((res) => {
          // do something with the response
          console.log(res);
        })
        .catch((err) => {
          // error uploading the data
          console.error(err);
        });
    });
  });
};

You can view the example code here.

Note that I don't have a valid URL so it will always error. You'll need to fill that in with the URL of your server.

Upvotes: 1

Related Questions