AWS Chalice Return an Image File from S3

ε祈祈猫儿з 提交于 2019-12-23 00:51:20

问题


I am using Chalice to build a simple severless application which returns an image file from S3.

I am able to return file after it is 64 bit encoded. But I am wondering how I can return the binary file so that user can take it as a file download? My following code is not working.

@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

回答1:


There was a bug in Chalice that was fixed on 14-May-2019:

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

I had a similar problem to yours and it's been fixed by grabbing the latest version of Chalice.




回答2:


Make sure the ContentHandling attribute of the IntegrationResponse is set to CONVERT_TO_BINARY. In the AWS console, navigate to the IntegrationResponse page for your binary method(s) and choose "Convert to binary (if needed)".

If you're comfortable with the CLI, you could also use a command like the following.

aws apigateway update-integration-response --rest-api-id foobar 
    --resource-id barfoo --http-method GET --status-code 200 
    --patch-operations op='replace',path='/contentHandling',value='CONVERT_TO_BINARY'


来源:https://stackoverflow.com/questions/44149971/aws-chalice-return-an-image-file-from-s3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!