简体   繁体   中英

Upload file to Django with Javascript

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?

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'})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM