【问题标题】:Upload file Vue 3 and Django REST上传文件 Vue 3 和 Django REST
【发布时间】:2021-05-13 01:22:42
【问题描述】:

如果我正确处理请求,我不明白,上传所有文件后都是 1 KB,我无法打开它们。如何创建正确的文件?如果我将文件另存为 .doc,我可以看到:

 ------WebKitFormBoundaryt3UjlK5SVq8hgppA
Content-Disposition: form-data; name="file"

[object FileList]
------WebKitFormBoundaryt3UjlK5SVq8hgppA--

所以我的函数要在 js 文件中提交:

async submitFiles() {

            let formData = new FormData();
            formData.append('file', this.file);
            console.log(this.file)

            axios.put(`/api/v1/myapp/upload/${this.file[0].name}`,
                formData,
                {
                    headers: {
                        'Content-Disposition': 'attachment',
                        'X-CSRFToken': await this.getCsrfToken(),
                    },

                }
            ).then(function () {
                console.log('SUCCESS!!');
            })
            .catch(function () {
                console.log('FAILURE!!');
            });

        },

处理表单文件的变化

        fileChanged(file) {
            this.file = file.target.files
        },

最后是我的 view.py

class FileUploadView(APIView):
    parser_classes = [FileUploadParser]

    def put(self, request, filename, format=None):

        file_obj = request.data['file']

        handle_uploaded_file(file_obj)
        return Response({'received data': request.data})

在哪里

def handle_uploaded_file(f):
    with open('path/to/my/folder/' + str(f.name), 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

【问题讨论】:

    标签: javascript python-3.x django django-rest-framework vuejs3


    【解决方案1】:

    [object FileList]

    哦,你序列化了整个FileList

    更改为:formData.append('file', this.file[0]);

    如果这不起作用,您可能需要阅读文件的内容。

    编辑:应该足够了,根据 MDN:

    字段的值。这可以是 USVString 或 Blob(包括 File 等子类)。如果没有指定这些值,则将值转换为字符串。

    【讨论】:

    • 谢谢,现在是解码错误,但我可以看到数据。 utf-8' codec can't decode byte 0x80 in position 42: invalid start byte
    • .txt 文件在哪里没有太大问题,因为我可以看到------WebKitFormBoundarygfCrlrL8otI2oR98 Content-Disposition: form-data; name="file"; filename="try.txt" Content-Type: text/plain If i can see it, it's working! ------WebKitFormBoundarygfCrlrL8otI2oR98--
    猜你喜欢
    • 2016-02-16
    • 2017-07-17
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 2013-12-26
    • 2021-08-21
    相关资源
    最近更新 更多