首页 > 解决方案 > request.FILES 返回 InMemoryUploadedFile

问题描述

我做了一个 api 来上传文件。为此,我使用了 Django 和 jQuery.ajax。我不知道如何阅读 File 这是我的 views.py 文件,它接收请求

def upload(request):
if request.method == 'POST':
    print(request.FILES['image'].file)
    data = request.FILES['image'].file.read()
    print(type(data))
    print(data)
    # data.encode()


    return JsonResponse(data={'message': 'recieved'})

这是我发送文件的 HTML 文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>

<form id="form">
    {% csrf_token %}
    <input type="file" id="inp-fld">
    <button type="submit">....</button>
</form>
</body>

<script type="text/javascript">

    const csrftoken = getCookie('csrftoken');



    jQuery.noConflict();
    formdata = new FormData();
    jQuery("#inp-fld").on("change", function() {
        var file = this.files[0];
        if (formdata) {
            formdata.append("image", file);
            console.log(formdata)
            jQuery.ajax({
                beforeSend: function(xhr){
                    xhr.setRequestHeader('X-CSRFToken', csrftoken)
                },
                url: "/upload",
                type: "POST",
                data: formdata,
                processData: false,
                contentType: false,
                success:function(data){
                    console.log(data)
                }
            });
        }
    });


    function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}



</script>

</html>

这是 request.files 的输出

<MultiValueDict: {'file': [<InMemoryUploadedFile: WIN_20190920_22_49_37_Pro.jpg (image/jpeg)>]}>

这是 (type(request.FILES.get('file').read())) 的输出

<class 'bytes'>

我怎样才能得到我上传的图像

我目前对图像处理和字节的想法和经验为 0

我只想将收到的文件转换为 jpg/jpeg

标签: javascriptjquerydjangoajax

解决方案


您可以将文件保存为:

f = request.FILES['file']
with open('some/file/name.txt', 'wb+') as destination:
    for chunk in f.chunks():
        destination.write(chunk)

一件重要的事情是:

FILESPOST仅当请求方法是并且<form>发布到请求的方法是“时才包含数据enctype="multipart/form-data。否则,FILES将是一个空白的类似字典的对象。

<form id="form", enctype="multipart/form-data>
.....
</form>

可以点击以下链接了解更多详情。

上传文件

例子


推荐阅读