首页 > 解决方案 > 通过 PUT 或 POST 为上传的文件添加了不必要的标头

问题描述

我用这个文档制作文件上传 APIhttps://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser

view.py

class FileUploadView(APIView):
    parser_classes = [FileUploadParser]

    def put(self, request, filename, format=None):
        file_obj = request.data['file']
        entry = WaveFile(document=file_obj) 
        entry.save()
        return Response(status=204)

然后在urls.py

urlpatterns += [
    re_path(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view())
]

模型如下所示

class WaveFile(models.Model):
    description = models.CharField(max_length=255, blank=True)
    document = models.FileField(upload_to='@_mat/_spleeter_wav/')
    uploaded_at = models.DateTimeField(auto_now_add=True)

现在我可以PUT像这样发送文件curl -X PUT -F upfile=_mat/e_h_01.jpg http://localhost:8008/upload/e_h_01.jpg

但是上传的文件被破坏了,因为文件附加了不必要的文件头。

--------------------------02d173694176f7aa
Content-Disposition: form-data; name="upfile"; filename="e_h_01.jpg"
Content-Type: image/jpeg

为什么会这样?如何从中提取文件本身request.data['file']

标签: pythondjangodjango-rest-framework

解决方案


推荐阅读