3

I have an extjs ajax function that send a form to the server which returns a file to download with the correct header. 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.

Is there a way to tell the ajax function that the file was correctly sent from the server or not?

  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
Below the Radar
  • 7,321
  • 11
  • 63
  • 142

1 Answers1

1

You can't download using 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.

Praise
  • 43
  • 6
  • You can return encoded binary data (base64 or else) to the browser from an ajax or xhr request, and then start the download using javascript. See my answer here: https://stackoverflow.com/a/47418911/1914034 – Below the Radar May 11 '20 at 19:57