【问题标题】:Upload File using Django Rest Framework使用 Django Rest 框架上传文件
【发布时间】:2013-10-25 17:05:03
【问题描述】:

我是 django 的新手。谁能帮我...我如何使用 Rest Framework API 上传文件?

我已尝试关注此页面:

http://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser

【问题讨论】:

  • 您实际尝试了什么?至少粘贴一些代码。
  • 我已经尝试了上面链接中给出的相同代码..现在我无法测试..如何测试?
  • @user2709881 看看这个blog post

标签: python django django-rest-framework serialization


【解决方案1】:

Django REST framework 中的文件上传与 django 中的 multipart/form 中的文件上传相同。

你可以使用 curl 来测试它:

curl -X POST -H "Content-Type:multipart/form-data" -u {username}:{password} \
-F "{field_name}=@{filename};type=image/jpeg" http://{your api endpoint}

其他字段就像 Django 中的普通表单字段。

【讨论】:

  • 如果你的 curl 同时有 json 数据和图片呢?
  • 我认为您也可以将这些数据添加为表单字段数据(在 -F 参数中)。因为我已经几个月没有研究 REST 框架了,所以忘记了我做了什么。
  • Leonid:你得到问题的答案了吗?我们可以同时json数据和图像吗?
  • @Leonid 查看此代码github.com/zheli/duego-photo-gallery。我记得我用这个成功了。您可以在 rest_api 应用程序中查看上传测试。
  • @Zhe 我无法让测试 APIClient 上传文件 - 我在 .post 调用中不断收到 UnicodeDecodeError。你必须做些什么才能让它工作吗?
【解决方案2】:

哲的回答很好。此外,您可以添加一些参数以查看响应。以这个为例:

curl -X PATCH --dump-header - -H "Content-Type:multipart/form-data" -u jorge:123456 -F "image=@/home/oscar/Pictures/dgnest/_MG_6445.JPG;type=image/jpeg" http://localhost:8000/api/project/3/

【讨论】:

    猜你喜欢
    • 2015-10-04
    • 2013-12-26
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多