Django - 通过ajax请求提供文件服务

问题描述 投票:3回答:1

我有一个extjs的ajax函数,它可以向服务器发送一个表单,然后返回一个带有正确头的文件下载。该文件可以通过浏览器的正常文件下载窗口下载。但是,ajax请求的成功回调函数没有被触发,而且ajax正在无限期地等待响应。

有没有办法告诉ajax函数,文件到底有没有从服务器端正确发送?

  exportLayer = function(node_id){
    Ext.Ajax.request({
      method: "GET",
      form: "exportForm",
      url: "/basqui/layer/shapefile/export/" + node_id + "/",
      success: function(r){
                  html = Ext.decode(r.responseText).html
                  Ext.get('pageContent').update(html);
               },
    });
  }

在服务器端,我有一个extjs的ajax函数。

    temp = tempfile.TemporaryFile()
    zip = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
    shapefileBase = os.path.splitext(dstFile)[0]
    shapefileName = os.path.splitext(layer.filename)[0]
    for fName in os.listdir(dstDir):
        zip.write(os.path.join(dstDir, fName), fName)
    zip.close()

    #delete temporary files
    shutil.rmtree(dstDir)

    #return the zip to user
    f = FileWrapper(temp)
    response = StreamingHttpResponse(f, content_type="application/zip")
    response['Content-Disposition'] = "attachment; filename=" + shapefileName + fileExt_dic[format]
    response['Content-Length'] = temp.tell()
    temp.seek(0)

    return response
python ajax django
1个回答
1
投票

你不能使用Jquery Ajax下载。响应将无法到达浏览器。我曾经遇到过这样的问题,我是这样解决的。

$(".dwnBtn").click(function(){
let url = "{% url 'the url'%}"
$.post(url, function(data)
{
    console.log(data);
    location.replace(url);
});

})这将使浏览器重新加载,然后下载你的文件。

© www.soinside.com 2019 - 2024. All rights reserved.