2

I have a html page that allows a user to take a screenshot from their camera. This screenshot is then rendered in the page with the function from main.js down below.

If i do console.log(image) i get image tag with a src to a blob:http that has the image.

Now for the fun part. I want to post this image to my api in django rest framework.

Basically how do i go from a blob image to a post request to the api?

I tried using $.ajax but I dont know how to format the "blob data" to be accepted for the "data:" parameter field in ajax.

Note also that i'm not using forms in the html, when i do that the html page gets refreshed as soon as i take a screenshot so the image does not stay on the page..

If I have to use forms in order to make this work, please let me know and I will try another approach.

main.js

async function grabFrame() {
  const img = await imageCapture.grabFrame();

  const url = URL.createObjectURL(await imageCapture.takePhoto());
  document.querySelector("img").src = url

  #id_image is where the screenshot is located
  const image = document.getElementById('id_image')
  console.log(image)

index.html

<button onclick="grabFrame()">Grab Frame</button>
<img id="id_image" style="width:320px; height:240px"/>

models.py

class Image(models.Model):
    image = models.ImageField(upload_to='media/')

serializer.py

class ScreenshotCreateSerializer(ModelSerializer):
    class Meta:
        model = Image
        fields = [
            'image'
        ]

views.py

class SaveScreenshot(CreateAPIView):
    serializer_class = ScreenshotCreateSerializer
    permission_classes = [AllowAny]


def home_view(request):
    return render(request, 'index.html', {})

what i tried in the main.js

// $.ajax({
  //   url: "/api/save_screenshot",
  //   type: "POST",
  //   processData: false,
  //   mimeType: "multipart/form-data",
  //   contentType: false,
  //   data: blob data?,
  //   success: function (data) {
  //          alert("Screenshot saved successfully!");
  //   },
  //   error: function (e) {
  //       console.log(e);
  //   }
  //   }).done(function(o) {

  //  });


haulvulgar
  • 98
  • 1
  • 6
  • The most important thing first: to comment out multiple lines of code, use `/* code here */` –  Apr 11 '22 at 22:47
  • Duplicate: [How can javascript upload a blob?](https://stackoverflow.com/questions/13333378/how-can-javascript-upload-a-blob) –  Apr 11 '22 at 22:49

0 Answers0