简体   繁体   English

Cherrypy 下载serve_file

[英]Cherrypy download serve_file

I am attempting to create a zip file and the allow it to be downloaded from the webpage.我正在尝试创建一个 zip 文件并允许从网页下载它。 I am able to get it to serve the file but instead of downloading in the browser, it makes the call and serves it as the body of the response.我可以让它为文件提供服务,但不是在浏览器中下载,而是进行调用并将其作为响应的主体。 I just want to download the file.我只想下载文件。

def download(self, **kwargs):
        filename = kwargs["filename"]
        path = os.path.join(os.getcwd(), filename)
        return cherrypy.lib.static.serve_file(path, "application/x-download", "attachment", os.path.basename(path))
download.exposed = True

When i use chrome's inspect tools on the response from /download i can see that the content-type and disposition headers are set as expected, and can see the zip content in the response section.当我对来自 /download 的响应使用 chrome 的检查工具时,我可以看到内容类型和处置标头已按预期设置,并且可以在响应部分中看到 zip 内容。 However, I just want to download the file.但是,我只想下载文件。 I had this working at one point but now can't seem to get it going again.我曾经有过这个工作,但现在似乎无法让它再次运行。

HTTP/1.1 200 OK
Content-Type: application/x-download
Server: CherryPy/18.6.1
Date: Wed, 01 Jun 2022 20:14:59 GMT
Last-Modified: Wed, 01 Jun 2022 20:04:11 GMT
Content-Disposition: attachment; filename="benny.txt"
Accept-Ranges: bytes
Content-Length: 14

I have a CherryPy application where I do something similar and it works.我有一个 CherryPy 应用程序,我在其中做类似的事情并且它可以工作。 Here is what the code I have looks like:这是我的代码的样子:

    def getzip(self, dirpath=None):
        zipfile = os.path.join(ziplink, 'hostmaps/%s' % dirpath)
        return static.serve_file(zipfile, 'application/x-download', 'attachment', os.path.basename(zipfile))

Using jinja2 template, I have a link to download the zip from the HTML like this:使用 jinja2 模板,我有一个从 HTML 下载 zip 的链接,如下所示:

<p><a href="getzip?dirpath={{ zipfile }}">Download zip archive</a></p>

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM