【问题标题】:How to get an image from the server with django and graphql?如何使用 django 和 graphql 从服务器获取图像?
【发布时间】:2020-12-27 23:45:43
【问题描述】:

我已经设法进行突变以上传、更新和打印图像。但是如何在查询中获取 base64 格式的图像文件?

class Image(models.Model):
    image = models.ImageField(blank=True, null=True, upload_to="uploads/images")
    product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True)

【问题讨论】:

  • 你考虑过在graphql中返回图片的路径吗?我问是因为 ImageField 将图像文件的字符串路径存储在您的设置所配置的媒体目录中。
  • 嗨。感谢您的评论。我想在查询中返回带有图像的文件。我将立即发布我的请求。

标签: django image file get graphql


【解决方案1】:

我编写自己的解决方案。 首先,我在 ImageType 对象中创建了一个新字段,以将图像文件存储在 base 64 中。此外,我验证了图像字段的值是否存在,并且写入的地址与硬盘上的现有文件相关联。 然后,当请求图像时,会出现一个名为 base64file 的新字段,其中包含存储的图像,然后可以在前端进行解码。 希望这对某人有帮助。这是我的代码:

class ImageType(DjangoObjectType):
    class Meta:
        model = Image
        filter_fields = {'product_id': ['exact'],
        interfaces = (relay.Node,)

    base64file = graphene.String()

    def resolve_base64file(self, info):
        if self is not None and self.image and hasattr(self.image, 'url'):
            if os.path.isfile(self.image.url):
                return base64.b64encode(self.image.read())
            else:
                return 'File not found'
        return ''

【讨论】:

  • 如果/当您开始将图像存储在与实际 Web 服务器不同的服务器上时,这将导致问题。
  • 另外,通过将 url 传递给浏览器,您可以允许浏览器使用它自己的缓存来更快地加载图像。通过在 Web 应用程序中加载它们,您会强制浏览器一遍又一遍地重新使用资源。
  • 我明白了,谢谢。那么,如果我使用的是 graphql,如何创建一个从后端获取图像的 endopint?
  • 客户端如何渲染图片?这就是必须改变的。
  • 它将使用 React 和 Apollo。取决于我如何发送它。
猜你喜欢
  • 2018-03-05
  • 2017-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-12
相关资源
最近更新 更多