python - 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)
解决方案
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)
推荐阅读
- python - 对于 Python,“import gcsfs”或“from google.cloud import storage”与 GCS 交互
- java - 如何在android上启用高精度gps定位模式
- jupyter-notebook - 使用证书授予 ngrok 和 Jupyteer Lab 的读写访问权限
- typescript - typescript 元素隐式具有“任何”类型,因为 X 类型的表达式不能用于索引 Y 类型
- .net - .net 核心中的 HttpUtility.UrlEncode
- xml - 转换分层 DOM 树 XML 文件:XSLT 能否转换为“扁平化”XML 文件而不会丢失数据?
- android - 如何找到用户触摸的坐标?
- xml - 将 xml 数据发送到 Yardi 数据库
- javascript - 我使用 splice 删除作为 props 传递的数组的元素,使用 indexOf 方法导航元素,而是删除了除 first1 之外的所有元素
- python - 网格不兼容的 Metpy mpcalc.absolute_vorticity()