简体   繁体   English

使用Javascript将文件上传到Django

[英]Upload file to Django with Javascript

I have simple fetch function and I want to upload an base64 image. 我有简单的提取功能,我想上传base64图像。 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: 我有简单的Django视图:

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. 当调用函数upload_to_server时,该视图成功执行,但是request.POST为空。 It shouldn't be empty, it should have key photo with that base64 value. 它不能为空,它应该具有具有该base64值的关键photo

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 并且我更改了django视图,因为数据在request.body ,而不在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. 照片是base64编码的,但我需要将其作为媒体文件。 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'})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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