简体   繁体   English

Django - 通过 ajax 请求提供文件

[英]Django - Serve files through ajax request

I have an extjs ajax function that send a form to the server which returns a file to download with the correct header.我有一个 extjs ajax 函数,它向服务器发送一个表单,该函数返回一个文件以使用正确的标头下载。 The file can be downloaded with the normal file download window of the browser.该文件可以通过浏览器的正常文件下载窗口进行下载。 However, the success callback function of the ajax request is not triggered and the ajax is pending indefinately waiting for a response.但是ajax请求的成功回调函数并没有触发,ajax一直在pending等待响应。

Is there a way to tell the ajax function that the file was correctly sent from the server or not?有没有办法告诉 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);
               },
    });
  }

server side:服务器端:

    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

You can't download using Jquery Ajax.您无法使用 Jquery Ajax 进行下载。 The response would just not get to the browser.响应不会到达浏览器。 I had this issue once and I solved it by doing this:我曾经遇到过这个问题,我通过这样做解决了它:

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

}) This would make the browser reload and then download your file. }) 这将使浏览器重新加载,然后下载您的文件。

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

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