python - AWS Chalice 从 S3 返回图像文件

标签 python amazon-s3 aws-api-gateway chalice

我正在使用 Chalice 构建一个简单的无服务器应用程序,该应用程序从 S3 返回图像文件。

我能够在 64 位编码后返回文件。但我想知道如何返回二进制文件以便用户可以将其作为文件下载?我的以下代码不起作用。

@app.route('/binary_object/{bucket}/{key}', methods=['GET', 'PUT'])
def binary_object(bucket, key):
    request = app.current_request
    if request.method == 'GET':
        try:
            file_path = '/tmp/{}_{}'.format(uuid.uuid4(), key)
            s3_client.download_file(bucket, key, file_path)
            file_size = os.path.getsize(file_path)
            headers = {'Content-Disposition': 'attachment; filename=\"' + key + '\"',
                       'Content-Type': 'application/octet-stream',
                       # 'Content-Type': 'image/*',
                       'Content-Length': str(file_size)}

            fsk = open(file_path, 'rb')
            return Response(body=fsk, headers=headers, status_code=200)
        except Exception as e:
            print e
            raise e

最佳答案

Chalice 中存在一个错误,已于 2019 年 5 月 14 日修复:

https://github.com/aws/chalice/issues/1095

我遇到了与您类似的问题,通过获取最新版本的 Chalice 已解决该问题。

关于python - AWS Chalice 从 S3 返回图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44149971/

相关文章:

python - VSCode Python 测试发现失败(2018 年 6 月)

Scala - 当文件路径不存在时读取 DataFrame

python - 如何使用具有特定 AWS 配置文件的 dask 从 s3 读取 Parquet 文件

android - 将图像上传到 Amazon S3

python - 使用 Flask 从静态之外的目录提供文件

python多处理星图进度条

python - pygame中的矩形不会一致移动

amazon-web-services - 如何统计CloudFormation模板生成的资源数量?

amazon-web-services - API Gateway 验证内容类型 header

amazon-web-services - 如何为 AWS API Gateway 资源启用 CORS