How to download a file with its original filename

2019-06-28 08:56发布

Once you upload a file to the blobstore, it renames it something like "s9QmBqJPuiVzWbySYvHVRg==". If you navigate to its "/serve" URL to download the file, the downloaded file is named this jumble of letters.

Is there a way to have the downloaded file retain its original filename when uploaded?

3条回答
啃猪蹄的小仙女
2楼-- · 2019-06-28 09:23

The code that you refer to is the key of the BlobInfo entity, but the original filename is stored as property.

If you want a simple way to download a file by its filename you can use this code that I use for my ServeHandler, it works for my needs, download a file by its filename instead of blobstore key:

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
  def get(self, resource):
    blobs = blobstore.BlobInfo.gql("WHERE filename = '%s'" %(urllib.unquote(resource)))
    if blobs.count(1) > 0:
        blob_info = blobstore.BlobInfo.get(blobs[0].key())
        self.send_blob(blob_info,save_as=True) 
查看更多
Fickle 薄情
3楼-- · 2019-06-28 09:27

In the GAE admin console, BLOB viewer section, when you view an individual BLOB there is a download button on the bottom right of the viewer, as shown in the screenshot below.

enter image description here

查看更多
贼婆χ
4楼-- · 2019-06-28 09:30

When the file is uploaded using the BlobUploadHandler the original filename is stored as name property in the newly created BlobInfo entity.

In the blob serve handler, you can specify that the blob should be returned as download attachment, and you can specify with what name should it be saved with

from google.appengine.ext import webapp
import urllib

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
  def get(self, blob_info_key=None):
    blob_info_key = str(urllib.unquote(blob_info_key))
    blob_info = retrieve_blob_info(blob_info_key)
    self.send_blob(blob_info, save_as=blob_info.filename)


blob_app = webapp.WSGIApplication([
  ('/_s/blob/([^/]+)', blob.ServeHandler),
], debug=config.DEBUG)
查看更多
登录 后发表回答