1

I have simple fetch function and I want to upload an base64 image. The function is as follows:

function upload_to_server(canvasData){
    console.log(canvasData); // that is data:image/png;base64,iVBORw0KGgoAAAANSUh.......
    return fetch(api_url, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: {photo: canvasData}
    }).then(function (value) {
        if(value.ok){
            return value.json().then(function (response) {
                debugger;
            })
        }
    }).catch(function (reason) {
        debugger;
    })
}

And I have simple django view:

def upload_image(request):
    print(request.POST)
    pdb.set_trace()

It goes successful to that view when function upload_to_server gets called, but request.POST is empty. It shouldn't be empty, it should have key photo with that base64 value.

Any idea what I do wrong?

9
  • would you be considering to use jQuery ajax? Also if you manually inspect the request in your web browser, is it a POST, and does it contain the canvasData in the payload? Commented Feb 6, 2018 at 9:48
  • It seems you need to JSON.stringify({photo: canvasData}) Commented Feb 6, 2018 at 9:51
  • have you checked if it's in request.FILES? Commented Feb 6, 2018 at 9:51
  • @Sraw I tried it. The same problem. Commented Feb 6, 2018 at 9:53
  • @kujosHeist Yes. That is also empty. But it should be in files, because base64 is just a string. Commented Feb 6, 2018 at 9:54

1 Answer 1

2

If someone else has the same problem. I solved it as follows.

I changed the body of fetch request to:

body: JSON.stringify({photo: canvasData})

and I changed django view, because data is in request.body and not in request.POST

import json
def upload_image(request):
    body = json.loads(request.body)
    photo = body['photo']
    // Rest of the code

EXTRA

The photo is base64 encoded but I needed it as media file. I converted it to media file and saved it to database as follows:

def upload_image(request):
    body = json.loads(request.body)
    photo = body['photo']
    img_format, img_str = photo.split(';base64,')
    ext = img_format.split('/')[-1]

    data = ContentFile(base64.b64decode(img_str), name='temp.' + ext)  # You can save this as file instance.
    try:
        n_file = Files()
        n_file.file = data
        n_file.save()
        return JsonResponse({'status': 'success'})
    except Exception as err:
        return JsonResponse({'status': 'failed'})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.