0

I'm using webcam.js to capture user's image during user's registration on my template.

It prompts user permission and, if agreed, enable a "Take picture" button on page. On click, it takes a snapshot on the user's webcam. All working until saving the picture to django's ImageField.

Although it recommends using AJAX (which I can't understand in a million years) to upload it to my server, I've modified a little to pass the base64 string through an hidden input field. I've also managed to decode the base64 string and save it as a file '.jpeg' on the server successfully. I wish to save it from the memory, without writing it to the disk.

On models.py, foto is the ImageField. I'm using Django 1.9.4 and Postgres 9.4

Enough talk, here's my coding attempt which saves everything but the image:

views.py

class view1(View):

    def post(self, request, *args, **kwargs):
        form = UserForm(request.POST or None)
        form.foto = b64decode(request.POST['foto'][-(len(request.POST['foto']) - 24):])
        #decoding 'foto' received from POST, some stripping is needed
        if form.is_valid():
            instance = form.save(commit=False)
            instance.save()
            return HttpResponseRedirect()
    else:
        return HttpResponseRedirect()

template

    <form>
            <input type='submit' value="Submit">
            <input type='hidden' id='foto' name='foto'> 
    </form>

  <!--- JS from webcam.js takes picture and pass b64 string to #foto--->
  <!--- document.getElementById('foto').value="'"+data_uri+"'"; added to function "take_snapshot" --->

Any suggestions on how to manage the b64 string on my view?

Felício
  • 155
  • 1
  • 12

1 Answers1

0

Alright, 3 days without any comments or answers, I've accomplished an workaround on my problem:

under the post method:

            img_data = b64decode(request.POST['foto'][-(len(request.POST['foto']) - 24):])
            fh = open(PATH.join(MEDIA_ROOT, 'img.jpeg'), 'w+b')
            fh.write(img_data)
            instance.foto = File(fh)
            instance.save()
            fh.close()

Some considerations are necessary though. This ain't a solution to write it directly from memory, it solves my specific problem. It might solve yours, so I'm sharing.

The main two reasons I've wanted to save it directly from memory were:

  1. To avoid unnecessary disk-readings, some may say they are SLOW
  2. To avoid file duplication

Number 1 is still a problem. I'm considering number 2 as not a problem, although this code still keeps a duplicated copy of the last image saved as 'img.jpg'. Go ahead and delete it afterwards if you want.

Anyway, I'm keeping this question open in case someone finds (and share) a better solution.

Felício
  • 155
  • 1
  • 12