首页 > 解决方案 > django rest 文件上传并返回链接

问题描述

我正在通过stackoverflow搜索工作fileupload APIView的示例(使用最新版本的DRF),我已经尝试了许多不同的代码示例,但没有一个有效(其中一些已被弃用,一些 - 不是我想要的)

我有这些模型:

class Attachment(models.Model):
    type = models.CharField(max_length=15, null=False)
    attachment_id = models.CharField(max_length=50, primary_key=True)
    doc = models.FileField(upload_to="docs/", blank=True)

我不想使用表单和其他任何东西,但我想在将来获得 POST 的字段(例如名称)

我相信解决方案很简单,但这不起作用

class FileUploadView(APIView):
    parser_classes = (FileUploadParser,)

    def post(self, request):
        file_obj = request.FILES
        doc = Attachment.objects.create(type="doc", attachment_id=time.time())
        doc.doc = file_obj
        doc.save()
        return Response({'file_id': doc.attachment_id}, status=204)

标签: pythondjangodjango-rest-framework

解决方案


removing parser_class will solve almost all problems here. Try the following snippet

class FileUploadView(APIView):

    def post(self, request):
        file = request.FILES['filename']
        attachment = Attachment.objects.create(type="doc", attachment_id=time.time(), doc=file)
        return Response({'file_id': attachment.attachment_id}, status=204)


Screenshot of POSTMAN console
enter image description here


推荐阅读