簡體   English   中英

Django - 通過 ajax 請求提供文件

[英]Django - Serve files through ajax request

我有一個 extjs ajax 函數,它向服務器發送一個表單,該函數返回一個文件以使用正確的標頭下載。 該文件可以通過瀏覽器的正常文件下載窗口進行下載。 但是ajax請求的成功回調函數並沒有觸發,ajax一直在pending等待響應。

有沒有辦法告訴 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);
               },
    });
  }

服務器端:

    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

您無法使用 Jquery Ajax 進行下載。 響應不會到達瀏覽器。 我曾經遇到過這個問題,我通過這樣做解決了它:

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

}) 這將使瀏覽器重新加載,然后下載您的文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM