在 App Engine 中,当用户访问静态文件(例如媒体文件)时,默认情况下,浏览器会尝试对文件进行流媒体播放。这对于某些类型的文件(如视频和音频)来说通常是理想的,但对于其他类型的文件(如图像和文档)来说,用户可能希望直接下载该文件。
为了强制浏览器下载文件,您可以在 App Engine 配置中设置 force_download
指令。这将告诉 App Engine 在用户访问文件时自动添加 Content-Disposition: attachment
头。
from google.appengine.api import app_identity
def force_download(filename, file_name):
"""
Forces the browser to download a file instead of displaying it.
Args:
filename: The name of the file to download.
file_name: The name of the file to display in the browser.
"""
bucket_name = app_identity.get_default_gcs_bucket_name()
blob_key = '{bucket_name}/{filename}'.format(
bucket_name=bucket_name, filename=filename)
disposition = 'attachment; filename="{filename}"'.format(filename=file_name)
headers = {'Content-Disposition': disposition}
blob_info = appengine_gcs.BlobInfo.get(blob_key)
blob_file = blob_info.open(headers)
return blob_file.read()
您还可以通过在请求中添加 force_download
参数来实现相同的目的。例如,以下请求将强制浏览器下载名为 image.jpg
的文件:
http://example.com/image.jpg?force_download=true
代码示例
以下是一个使用 App Engine 内置 appengine_gcs
库实现强制下载功能的示例:
from google.appengine.api import app_identity
from google.appengine.api import appengine_gcs
def force_download(filename, file_name):
"""
Forces the browser to download a file instead of displaying it.
Args:
filename: The name of the file to download.
file_name: The name of the file to display in the browser.
"""
bucket_name = app_identity.get_default_gcs_bucket_name()
blob_key = '{bucket_name}/{filename}'.format(
bucket_name=bucket_name, filename=filename)
disposition = 'attachment; filename="{filename}"'.format(filename=file_name)
headers = {'Content-Disposition': disposition}
blob_info = appengine_gcs.BlobInfo.get(blob_key)
blob_file = blob_info.open(headers)
return blob_file.read()
这个函数接受两个参数:filename
和 file_name
。filename
是要下载的文件的名称,file_name
是要在浏览器中显示的文件的名称。
函数首先获取 App Engine 默认的 GCS 存储桶名称。然后,它创建一个 BlobKey,该 BlobKey 由存储桶名称和文件名组成。
接下来,函数创建一个 HTTP 头字典,其中包含 Content-Disposition
头。Content-Disposition
头告诉浏览器将文件下载到用户的计算机而不是在浏览器中显示它。
最后,函数获取 BlobInfo 对象,然后使用 open()
方法打开 BlobFile 对象。open()
方法接受一个字典作为参数,该字典包含要发送的 HTTP 头。
函数将 BlobFile 对象的内容读入内存,然后将这些内容返回给调用者。调用者可以将这些内容写入文件,或者将其发送给浏览器。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。