-2

我正在使用 ajax 向我的 django 函数发送请求,然后生成一个 zip 文件并将其提供给用户。如果我转到该 url domain.com/django/builder/zipit/,文件会按预期生成并下载到我的计算机,但是当使用 ajax 并返回响应时,ajax 无法下载它。我可以将响应传递给 php 变量并以这种方式下载吗?使用 iframe 将不起作用,因为该文件是动态创建的。

阿贾克斯

$.ajax({
    type: 'POST',
    url: '/django/builder/zipit/',
    data: serialize,
    success: function(response){
        //pass response to php somehow
    }

视图.py

def send_zipfile(request):
temp = tempfile.TemporaryFile()
archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
filename = '/home/dbs/public_html/download/video.html'
archive.write(filename, 'file.html')
archive.close()
wrapper = FileWrapper(temp)
response = HttpResponse(wrapper, content_type='application/zip', mimetype='application/x-download')
response['Content-Disposition'] = 'attachment; filename=dbs_content.zip'
response['Content-Length'] = temp.tell()
temp.seek(0)
return response
4

1 回答 1

0

您不需要将它传递给 PHP 变量。在 django 本身中一切皆有可能。

mimetype 设置为 application/x-zip-compressed

但请注意,在每个请求上创建 zip 存档是个坏主意,这可能会杀死您的服务器(如果存档很大,则不计算超时)。性能方面的方法是将生成的输出缓存在文件系统中的某处,并仅在源文件发生更改时重新生成它。更好的主意是提前准备档案(例如,通过 cron 作业)并让您的 Web 服务器像往常一样为它们提供服务。

# archive_list = ["ZipTest1.txt", "ZipTest2.txt", "ZipTest3.txt"]
# # save the files in the archive_list into a PKZIP format .zip file
# zfilename = "Wife101.zip"
# zout = zipfile.ZipFile(zfilename, "w")
# for fname in archive_list:
# zout.write(fname)
# zout.close()
return HttpResponse(zout,mimetupe="application/x-zip-compressed")
于 2012-06-14T06:48:32.783 回答