簡體   English   中英

上傳文件 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:

字段的值。 這可以是 USVString 或 Blob(包括 File 等子類)。 如果沒有指定這些值,則將值轉換為字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM