从GAE blob下载时用Python编码文件名

2024-10-04 11:21:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个简单的应用程序,提示用户选择一个文件上传,然后在网页上列出,可供下载。我正在使用Blobstore来执行这些操作。 该应用程序还应适用于包含非ASCII字符(如中文和日文)的名称文件。 我已经管理应用程序,以正确地上传和列出这些名字的文件使用以下代码在主.py地址:

class MainScreen(BaseHandler):
    def get(self):
        upload_url = blobstore.create_upload_url('/upload')
        uploadedBlobs[]
        for item in blobstore.BlobInfo.all():
            uploadedBlobs.append(str(item.key(),item.filename)) 
        #uploadedBlobs is a list of tuples each containing two elements: blob key and blob name (file name) which is then sent to template (main.html)
        template_values = {
        'formAction': upload_url,
        'listofBlobs': uploadedBlobs, 
        }
        template = JINJA_ENVIRONMENT.get_template('main.html')
        self.response.write(template.render(template_values))

class FileUploadHandler(blobstore_handlers.BlobstoreUploadHandler,BaseHandler):
    def post(self):
        upload = self.get_uploads('file')
        blob_info = upload_files[0]
        self.redirect('/')


class ViewFiles(blobstore_handlers.BlobstoreDownloadHandler,BaseHandler):
    def get(self, blob_key):
         blob_key = str(urlib.unquote(blob_key))
         blob_info = blobstore.BlobInfo.get(blob_key)
         self.send_blob(blob_info, save_as=urlib.quote(blob_info.filename.encode('utf-8')))

然后在模板中(主.html)我使用以下代码解码文件名并正确显示它们:

{%for item in listOfBlobs%}
    <li><a href="/serve/{{item[0]}}">{{item[1]}}</a></li>
{% endfor %}

问题是,当我单击链接下载一个非ASCII名称的文件时,它的名称没有正确地保存在本地驱动器上,而是采用如下形式: %E4%B8%广告.txt(对于名称为:本語.txt或.txt的文本文件)。对于名称中仅使用ASCII的文件,一切正常。 有没有人知道如何让浏览器用文件中显示的名称保存文件,而不是将其转换为十六进制的Unicode字符串(我相信)? 非常感谢您的帮助。你知道吗


Tags: 文件keyselfinfo名称getasciitemplate