Spring MVC download content of String as text file

To download a text file out of a String :

JSP View :
 <a href="download">Download String </a> 

Controller Method :

 @RequestMapping(value = "/download", method = RequestMethod.GET)
 public @ResponseBody
 void downloadFile(HttpServletResponse resp) {
  String downloadFileName= "download.txt";
  String downloadStringContent= getStringToWrite(); // implement this
  try {
   OutputStream out = resp.getOutputStream();
   resp.setContentType("text/plain; charset=utf-8");
   resp.addHeader("Content-Disposition","attachment; filename=\"" + downloadFileName + "\"");
   out.write(downloadStringContent.getBytes(Charset.forName("UTF-8")));
   out.flush();
   out.close();

  } catch (IOException e) {
  }
 }

Check this as well : spring mvc download a file from server

Spring MVC file download from server example code

To download a file - from request parameter

JSP View :
 <a href="downloadFile?fileName=log.txt">Download String </a> 

Controller Method :


@RequestMapping(value = "/downLoadFile", method = RequestMethod.GET)
public void downLoadFile( HttpServletRequest request, HttpServletResponse response ) {
try {
 String fileName = request.getParameter( "fileName" );
 File file = getFileToDownload(fileName) // implement this to return a valid file object
 InputStream in = new BufferedInputStream( new FileInputStream( file ) );

 response.setContentType( "text/plain" ); // define your type
 response.setHeader( "Content-Disposition", "attachment; filename=" + fileName  );

 ServletOutputStream out = response.getOutputStream( );
 IOUtils.copy( in, out ); //import org.apache.commons.io.IOUtils;
 response.flushBuffer( );
} catch ( Exception e ) {
 e.printStackTrace( );
}
}