简体   繁体   中英

Download png file after XMLHttpRequest POST

I have a website that sends data in the form of a standard XMLHttpRequest to a java servlet as follows

var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", "/GraphingServlet/FC/ExportPng", false);
xmlHttp.send("some_data");

My java servlet recieves this request, creates a png in binary encoding and sends this png back to the website doing the something along the lines of the following

response.setContentType("image/png");
response.setHeader("Content-Disposition","attachment; filename=\"picture.png\"");
response.setHeader("Content-Transfer-Encoding", "binary");
ServletOutputStream out = response.getOutputStream();
out.write(byte_array_of_binary_encoded_png);
out.flush();

Through firebug I see that my webpage recieves a whole lot of information but I get no download popup. How do I get the website to prompt the user to save this png as "picture.png" upon recieving the png encoded within the http response?

Help is appreciated.

You can not download files via AJAX. However, you can do the following:

HTML :

<button type="button" onclick="download()">Donwload</button>

<form name="downloadForm" action="/GraphingServlet/FC/ExportPng"
  method="post" target="secretFrame" style="display: none;">
  <input type="hidden" id="param1" name="param1"> 
  <input type="hidden" id="param2" name="param2">
</form>

<iframe name="secretFrame" style="display: none;"></iframe>

JS :

function download() {
  document.getElementById("param1").value = "some_data";
  document.getElementById("param2").value = "some_data";
  document.forms["downloadForm"].submit();
}

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