简体   繁体   中英

Implement file download from REST service in webapp

I have a simple webapp which I intend to serve a file download from a REST api. The file is of type .xlsx.

My naive attempt to accomplish this uses a design pattern that I have copied from other data pulls from the REST api for example:

  var requestData = JSON.stringify({level: plevel, yearMonthStart: beginningYearmo, yearMonthEnd: endingYearmo});
  var url = 'http://localhost:8181/v2/file/download';
  d3.request(url)
    .header("X-Requested-With", "XMLHttpRequest")
    .header("Content-Type", "application/octet-stream")
    .mimeType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    .send("POST",
          requestData,
          function(rawData){
             console.log(rawData);
       });

The response from the server is a 415 error code (unsupported payload media type).

I have tried to set the appropriate headers for the filestream as can be seen above.

My expected behaviour is that the request is accepted without error and the browser initiates a file download. Any guidance here on how to better accomplish this would be appreciated.

I found some examples in other posts that light the way.

You can do this using blob files. Here's an example:

function downloadReport(level, beginningYearmo, endingYearmo){
  var requestData = JSON.stringify({plevel: level, yearMonthStart: beginningYearmo, yearMonthEnd: endingYearmo});
  var url = 'http://localhost:8181/file/download';
  d3.request(url)
    .header("X-Requested-With", "XMLHttpRequest")
    .header("Content-Type", "application/json")
    .header("Accept","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    .header("Cache-Control", "no-cache")
    .header("Accept-Charset", "utf-8")
    .on("load", function(data){
      var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
      var objectUrl = URL.createObjectURL(blob);
      window.open(objectUrl);
      console.log("Download request was successful.");
    })
    .on("error", function(error){ alert("Error: ", error) })
    .send("POST", requestData);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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