1

I found this code of Gourav. If I call the servlet from the browser it works but if I use a "POST" call with AJAX, it only recovers the text but does not automatically download the file..

Can anyone explain how I can do this? Thank you!

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     response.setContentType("text/plain");
     response.setHeader("Content-Disposition", "attachment; filename=\"myTxtFile.txt\"");

     StringBuilder sb = new StringBuilder();
     sb.append("Lorem ipsum dolor sit amet, consectetur elit.");
     sb.append(System.getProperty("line.separator"));
     sb.append("parturient montes, nascetur ridiculus mus.");
     sb.append(System.getProperty("line.separator"));
     sb.append("Duis magna neque, malesuada non condimentum posuere.");

     OutputStream outputStream = response.getOutputStream();

     String outputResult = sb.toString();
     outputStream.write(outputResult.getBytes());
     outputStream.flush();
     outputStream.close();

}

pigobyte
  • 95
  • 7
  • It's not possible to download a file (that is write it to disk) with AJAX/JavaScript. Have a look at https://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax – RoToRa Dec 30 '21 at 12:50

0 Answers0