Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

javascript - Download file via jquery ajax post

I am trying to export my web page data and download it as excel file. but the download does not start even the response return succeed.

$.ajax({
      type: "POST",
      url: _url,
      contentType: 'multipart/form-data;boundary=SzB12x',
      data: json,
    });

The responseText something like this:

PK?J;Fxl/theme/theme1.xml?YOo?6????,[r??n;v??i????#-?kJH:?oC{0X7?2??mZ???d??u@?(?b:M?????????{|??^?0t@??*"w$?!0I?[??n?i??'????iH? g?,??|?J?!???hRh?h???r&?L ????S??v@???#????"???}??Жt%?hR?t"??????+????????u{???0K???oy?9OTWywkA?? ???F?? 6*?????[???U???

I think its the file but I cant download it!!

Any help please?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I faced the same issue and successfully solved it. My use-case is this.

  • Post JSON data to server and receive an excel file.
  • That excel file is created on the fly and returned as a response to client.

Code:

$("#my-button").on("click", function() {
    // Data to post
    data = {
        ids: [1, 2, 3, 4, 5]
    };

    // Use XMLHttpRequest instead of Jquery $ajax
    xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        var a;
        if (xhttp.readyState === 4 && xhttp.status === 200) {
            // Trick for making downloadable link
            a = document.createElement('a');
            a.href = window.URL.createObjectURL(xhttp.response);
            // Give filename you wish to download
            a.download = "test-file.xls";
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
        }
    };
    // Post data to URL which handles post request
    xhttp.open("POST", excelDownloadUrl);
    xhttp.setRequestHeader("Content-Type", "application/json");
    // You should set responseType as blob for binary responses
    xhttp.responseType = 'blob';
    xhttp.send(JSON.stringify(data));
});

The above snippet is just doing following

  • Posting an array as JSON to the server using XMLHttpRequest
  • After fetching content as a blob(binary), we are creating a downloadable URL and attaching it to invisible "a" link then clicking it.

Here we need to carefully set few things at the server side. I set few headers in Python Django HttpResponse. You need to set them accordingly if you are use other programming languages.

# In python django code
response = HttpResponse(file_content, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")

Since I download xls(excel) here, I adjusted contentType to above one. You need to set it according to your file type.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...