如何使用jQuery ajax在web2py中下载(zip)文件

时间:2015-09-28 19:04:23

标签: ajax download web2py

zip文件以'download_data'编写,返回时没有错误或下载响应。

注意:

  • 从函数返回的打印数据似乎是zipfile数据

  • 我没有增加或利用download.stream或response.download,也不知道在这种情况下是否有必要

请指出以下ajax调用和/或控制器函数中缺少的内容,以生成zip文件下载。

jQuery.ajax({method:'get',url:'{{=URL('download_data')}}',
                data:fileIDs,
                success: function(){}

                });

# function in web2py controller
def download_data():
    import zipfile
    import cStringIO
    import contenttype as c
    vars = request.vars
    tempfile = cStringIO.StringIO()
    temparchive = zipfile.ZipFile(tempfile, 'w', zipfile.ZIP_DEFLATED)

    fileIDs = vars.values()
    try:
        for file_id in fileIDs:
            file = db.files[file_id].file
            fileLoc = db.files.file.retrieve_file_properties(file)['path'] + '/' + file
            temparchive.writestr(db.files[file_id].file_name, open(fileLoc, 'rb').read())

    finally:
        temparchive.close() #writes 
        response.headers['Content-Disposition'] = 'attachment;filename=files.zip'
        response.headers['Content-Type'] = 'application/zip'
        rtn = tempfile.getvalue()
        tempfile.close()
    return rtn

1 个答案:

答案 0 :(得分:0)

从技术上讲,下载不能由ajax请求触发。您必须将window.location设置为文件' URL(在web2py中这是返回文件数据的控制器函数的URL),或者依赖于当前可疑的'下载html5规范。

有关详细信息,请参阅https://codex.wordpress.org/Option_Reference以及此问题的web2py来源:Download a file from Servlet using Ajax

相关问题