简体   繁体   English

服务器端 python 返回一个 zip 文件以供下载

[英]Server-side python returning a zip file for a download

Using my client I pass a parameter by get to a python script on the server, it runs a process and creates a zip file.使用我的客户端,我通过 get 到服务器上的 python 脚本传递一个参数,它运行一个进程并创建一个 zip 文件。 In my client side JavaScript my ajax call just tells me it was able to pass the data to my python script.在我的客户端 JavaScript 中,我的 ajax 调用只是告诉我它能够将数据传递给我的 python 脚本。

I've tried sys.stdout.write(b"zipfilename") but nothing happens.我试过sys.stdout.write(b"zipfilename")但没有任何反应。 If I can't pass the file back, is there a way to pass something back so my JavaScript knows it's done?如果我无法将文件传回,有没有办法传回一些东西,以便我的 JavaScript 知道它已完成? I'm not using NODE or Angular.我没有使用 NODE 或 Angular。 My python script does run and creates the zip file on the server but the JavaScript page doesn't know it nor does a download dialog appear.我的 python 脚本确实运行并在服务器上创建了 zip 文件,但 JavaScript 页面不知道它,也没有出现下载对话框。 I'm missing something basic but I can't find it.我缺少一些基本的东西,但我找不到它。

My JS AJAX call:我的 JS AJAX 调用:

 $.ajax({ url: theUrl, type: 'get', success: function(response){ } });

The end of my python script:我的python脚本结束:

def createZip(v, charset=None):

    with ZipFile(v +'.zip', 'w') as myzip:
        myzip.write(v +'.shp')
        myzip.write(v +'.shx')
        myzip.write(v +'.dbf')
        myzip.write(v +'.prj')

    return 'c:/dev/python/'+ v + '.zip'

createZip(fn)

It's hard to tell based on the limited code provided, but here's some general points:根据提供的有限代码很难判断,但这里有一些一般要点:

  • sys.stdout.write is going to write to the output of the application running the Python script, not to a HTTP response (unless it's running as a WSGI application). sys.stdout.write将写入运行 Python 脚本的应用程序的输出,而不是写入 HTTP 响应(除非它作为 WSGI 应用程序运行)。
  • If you are writing the HTTP response in a WSGI type of application, then you're going to need to include the entire HTTP response body, including the multipart and content type headers so that the browser knows what is coming back (otherwise it's just a feed of meaningless bytes).如果您在 WSGI 类型的应用程序中编写 HTTP 响应,那么您将需要包含整个 HTTP 响应主体,包括多部分和内容类型标头,以便浏览器知道返回的内容(否则它只是一个无意义字节的馈送)。
  • A download prompt will only appear if the browser loads a page which returns a application/octet-stream content type (or the download attribute is set on the anchor which links to the file).仅当浏览器加载返回应用程序/八位字节流内容类型的页面(或在链接到文件的锚点上设置download属性)时,才会出现下载提示。
  • An AJAX call wouldn't cause a download to occur in the foreground browser, it would appear in your developer tools 'Network' tab and the AJAX response variable would contain the data, but this isn't automatically pushed to the browser as a downloadable file. AJAX 调用不会导致在前台浏览器中进行下载,它会出现在您的开发人员工具“网络”选项卡中,并且 AJAX 响应变量将包含数据,但这不会作为可下载文件自动推送到浏览器文件。

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

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