上传文件 Vue 3 和 Django REST

Upload file Vue 3 and Django REST

我不知道我是否正确处理了请求,上传后所有文件都是 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)

[object FileList]

哦,你连载了整个FileList

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

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

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

The field's value. This can be a USVString or Blob (including subclasses such as File). If none of these are specified the value is converted to a string.