【问题标题】:request.FILES returns InMemoryUploadedFilerequest.FILES 返回 InMemoryUploadedFile
【发布时间】:2020-07-22 19:05:06
【问题描述】:

我做了一个 api 来上传文件。为此,我使用了 Django 和 jQuery.ajax。我不知道如何阅读文件 这是我收到请求的 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

【问题讨论】:

    标签: javascript jquery django ajax


    【解决方案1】:

    您可以将文件保存为:

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

    重要的是:

    FILES 仅在请求方法为 POST 并且发布到请求的 &lt;form&gt; 具有 enctype="multipart/form-data" 时才会包含数据。否则,FILES 将是一个空白字典类对象.

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

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

    File upload

    Example

    【讨论】:

    • 我如何在ajax中定义enctype="multipart/form-data
    • &lt;form&gt; 应该有enctype="multipart/form-data 属性,你可以在form 标签中提及这个。
    • 这是 request.FILES &lt;MultiValueDict: {'file': [&lt;InMemoryUploadedFile: WIN_20190920_22_49_37_Pro.jpg (image/jpeg)&gt;]}&gt; 的输出,这是 form.errors&lt;ul class="errorlist"&gt;&lt;li&gt;file&lt;ul class="errorlist"&gt;&lt;li&gt;This field is required.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt; 的输出,这是我的 forms.py class FileForm(forms.ModelForm): class Meta: model= temp fields = '__all__'
    • 以上是您如何上传和保存文件的解决方案,因为您提到转换为文件 jpeg/jpg,我没有得到您想要实现的确切内容,无论如何 request.FILES 打印是正确的。仅供参考,如果我们 print(obj) 任何不意味着它打印其实际值/属性的对象,请尝试搜索工作 __str____repr__。无论如何,如果您进一步遇到任何错误,只需编辑您的问题并包含所有相关代码以及完整的错误回溯。
    • 我知道__str__ 和其他方法我只想看到我上传的图像我应该写什么视图函数
    猜你喜欢
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多