【问题标题】:Show Image stored in s3 on Web page using flask使用烧瓶在网页上显示存储在 s3 中的图像
【发布时间】:2020-09-14 17:36:00
【问题描述】:

我正在尝试从 s3 存储桶中获取图像,并使用烧瓶(以及使用 boto3 访问存储桶)将它们显示在网页上。

我目前有一个桶中所有图片的列表,但无法获取 html 来显示它们(给我 404 错误)。

如何在不下载文件的情况下执行此操作? 这是我目前所拥有的:

def list_files(bucket):
    contents = []
    for image in bucket.objects.all():
        contents.append(image.key)
    return contents

def files():
    list_of_files = list_files(bucket)
    return render_template('index.html', my_bucket=bucket, list_of_files=list_of_files)

这是 html sn-p:

<table class="table table-striped">
        <br>
        <br>
        <tr>
          <th>My Photos</th>
           {% for f in list_of_files %}
            <td> <img src="{{ f }}"></td>

            {% endfor %}

非常感谢!

【问题讨论】:

    标签: flask amazon-s3 boto3


    【解决方案1】:

    因为将图像加载到 html 页面需要目录中存在的真实图像。如果您先在目录中下载它们,则可以将来自 AWS S3 的图像加载到 html 页面上,然后使用其 url 作为 html &lt;image&gt; 标签中的源。

    我找到了解决方案,但您需要根据需要对其进行修改。 定义一个从 S3 加载图像的函数:

    import matplotlib.image as mpimg
    import numpy as np
    import boto3
    import tempfile
    
    s3 = boto3.resource('s3', region_name='us-east-2')
    bucket = s3.Bucket('bucketName')
    object = bucket.Object('dir/subdir/2015/12/7/img01.jpg')
    tmp = tempfile.NamedTemporaryFile()
    
    def imageSource(bucket, object, tmp):
           with open(tmp.name, 'wb') as f:
                object.download_fileobj(f)
                src = tmp.name    #dir/subdir/2015/12/7/img01.jpg
                retrun src
    

    【讨论】:

      【解决方案2】:

      刚刚也遇到了这个问题,好像很久没更新了,试试补充吧。

      您当前的以下方法是正确的。唯一的问题是,为了呈现不会下载到您的服务器的图像,您必须有一个指向您的 S3 文件的直接 url。目前,您只有图像名称,而不是完整的 url。

      def list_files(bucket):
      contents = []
      for image in bucket.objects.all():
          contents.append(image.key)
      return contents
      
      def files():
          list_of_files = list_files(bucket)
          return render_template('index.html', my_bucket=bucket, list_of_files=list_of_files)
      

      目前,您在文件列表中的项目将如下所示:

      ['file_name1', 'file_name2', 'file_name3']
      

      为了让它们直接在您的浏览器中呈现,您需要它们看起来像这样:

      ['file_url1', 'file_url2', 'file_url3']
      

      s3 文件 url 看起来像这样:https://S3BUCKETNAME.s3.amazonaws.com/file_name1.jpg

      因此,而不是下面的行

      contents.append(image.key)
      

      您需要将 image.key 替换为构成 URL 的内容

      contents.append(f'https://{S3BUCKETNAME}.s3.amazonaws.com/{image.key})
      

      应该可以,您拥有的 html 应该可以正常工作。唯一的另一个大风险是您上传的文件不是公开的,因为您需要查看 AWS 上存储桶的设置。

      其他资源和来源:

      1. 向您的 AWS S3 存储桶添加公共策略:https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-bucket-policies.html
      2. 使用 Flask 和 S3 上传和下载文件:https://stackabuse.com/file-management-with-aws-s3-python-and-flask/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多