使用Google App Engine Blobstore下载文件名

not*_*ans 10 python google-app-engine blobstore

我正在使用Google App Engine Blobstore来存储一系列文件类型(PDF,XLS等),并且我正在尝试找到一种机制,通过该机制可以使用上传文件的原始文件名(存储在blob_info中)来命名下载的文件,即用户在保存对话框中看到'some_file.pdf'而不是'very_long_db_key.pdf'.

我在文档中看不到任何允许这样的内容:

http://code.google.com/appengine/docs/python/blobstore/overview.html

我在其他帖子中看到了一些提示,你可以使用blob_info中的信息来设置content-disposition头.这是实现理想目标的最佳方法吗?

Kev*_*n P 12

send_blob函数中有一个可选的'save_as'参数.默认情况下,此值设置为False.将其设置为True将导致文件被视为附件(即它将触发"保存/打开"下载对话框),用户将看到正确的文件名.

例:

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, resource):
        resource = str(urllib.unquote(resource))
        blob_info = blobstore.BlobInfo.get(resource)
        self.send_blob(blob_info,save_as=True)
Run Code Online (Sandbox Code Playgroud)

也可以通过传入一个字符串来覆盖文件名:

self.send_blob(blob_info,save_as='my_file.txt')
Run Code Online (Sandbox Code Playgroud)

如果您想要打开某些内容(例如pdfs)而不是保存,则可以使用content_type来确定行为:

blob_info = blobstore.BlobInfo.get(resource)
type = blob_info.content_type
if type == 'application/pdf':       
    self.response.headers['Content-Type'] = type
    self.send_blob(blob_info,save_as=False)
else:
    self.send_blob(blob_info,save_as=True)
Run Code Online (Sandbox Code Playgroud)