【问题标题】:how to convert an InMemoryUploadedFile upload to cloudinary in Django=1.11 using cloudinary.uploader.upload()如何使用 cloudinary.uploader.upload() 在 Django=1.11 中将 InMemoryUploadedFile 上传转换为 cloudinary
【发布时间】:2018-05-07 03:52:36
【问题描述】:
  1. 我正在尝试将图像文件上传到我已从 django 模板发送到 views.py 中的函数的 cloudinary
  2. 文件在 request.FILES['image']

            cloudinary.config(
                cloud_name="p*****",
                api_key="33************",
                api_secret="4***-S***_o*********"
            )
            img_obj = request.FILES['image']
            cloudinary_response = cloudinary.uploader.upload(img_obj)
            image_url = cloudinary_response['url']
    
  3. 打印 img_obj 给出图像的名称(如:“tree.jpg”)

  4. cloudinary上传文档如下https://cloudinary.com/documentation/image_upload_api_reference#upload

  5. img_obj 的类型是 InMemoryUploadedFile。现在有没有办法将其转换为 base64 或类似的东西,以便我可以上传。

  6. 或任何其他解决方案?

【问题讨论】:

标签: django file-upload base64 cloudinary


【解决方案1】:

你有几个选择:

  1. img_obj.file 是实际的文件对象,因此您可以尝试直接上传。
  2. 由于InMemoryUploadedFileFile 的子类,您也可以只使用open(mode='rb') 文件,使用标准的python 文件io 函数。
  3. 或者你可以试试img_obj.file.read()

我会选择第二个选项:

import base64

with img_obj.open("rb") as image_file:
     encoded_string = base64.b64encode(image_file.read())

【讨论】:

  • 这应该可以解决问题。但不幸的是,这样做会引发异常 exit
  • 你能显示回溯吗?究竟是什么异常?
猜你喜欢
  • 2019-12-08
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-04
  • 1970-01-01
  • 2020-05-30
  • 2022-10-13
相关资源
最近更新 更多