【问题标题】:How to retrieve image files from mongodb to html page如何从 mongodb 检索图像文件到 html 页面
【发布时间】:2014-01-10 04:18:08
【问题描述】:

我已经成功地将图像文件以二进制格式存储在 mongdb 中。但是当我从 mongodb 获取图像时,我得到了相同的二进制格式。但是我需要这个图像文件。请有人帮忙

这是我使用的代码

def retrieve(request):

  db=pymongo.connection.Connection('localhost',27017).demo1
  grid=gridfs.GridFS(db)
  output=grid.get_last_version(filename='shiva.jpg')
  return HttpResponse(output)

【问题讨论】:

  • 我在 Web 开发环境中没有使用 Python 的经验,但是您是否可能需要将 HTTP 响应标头中的 mime-type 设置为 image/jpeg 以便用户使用 Web 浏览器知道它收到图像了吗?
  • 希望我在另一个问题上的回答可能对您有所帮助。 stackoverflow.com/questions/22077720/…
  • 希望我在另一个问题上的回答可能对您有所帮助。 stackoverflow.com/questions/22077720/…

标签: python django image mongodb gridfs


【解决方案1】:

您好,我已经成功地使用 python 从 mongodb 插入和检索了图像..

def insert_image(request):
    with open(request.GET["image_name"], "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())
    print encoded_string
    abc=db.database_name.insert({"image":encoded_string})
    return HttpResponse("inserted")

def retrieve_image(request):
    data = db.database_name.find()
    data1 = json.loads(dumps(data))
    img = data1[0]
    img1 = img['image']
    decode=img1.decode()
    img_tag = '<img alt="sample" src="data:image/png;base64,{0}">'.format(decode)
    return HttpResponse(img_tag)

【讨论】:

  • 对不起,我是 python 新手,什么是“rb”?并且“image_name”是指我们存储图像的变量的名称吗?
  • 转储(数据)是什么意思?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-05
  • 1970-01-01
  • 2020-08-14
  • 2014-12-05
相关资源
最近更新 更多