How to download PDF file from url on MVC controller

To download a remote file (like a PDF) redirecting to response output, use these instructions to update a your Spring MVC controller:

@RequestMapping(value="/viewAttach", method = RequestMethod.GET)
public ModelAndView viewAttach(@RequestParam(value="article_id", required = true) String article_ref, HttpSession session, HttpServletResponse response) 
{
	/* *** Remember to check if Session still valid  *** */
	try {
 
		URL url = new URL(remoteURL);        	
		response.setHeader("Content-disposition", "attachment;filename=" + filename);
 
		//Set the mime type for the response
		response.setContentType("application/pdf");
 
		// URLConnection connection = url.openConnection();
		InputStream is = url.openStream();
 
		BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
		int len;
		byte[] buf = new byte[1024];
		while ( (len = is.read(buf)) > 0 ) {
			outs.write(buf, 0, len);
		}
		outs.close();
 
	} catch (MalformedURLException e) {
		logger.error("Error ModelAndView.viewMain - MalformedURLException : " + e.toString() + " -- " + e.getStackTrace()[0].toString());
		return null;
	} catch (IOException e) {
		logger.error("Error ModelAndView.viewMain - IOException : " + e.toString() + " -- " + e.getStackTrace()[0].toString());
		return null;
	}
 
	return null;
 
}
Tagged ,

One thought on “How to download PDF file from url on MVC controller

  1. […] method standard servlet download code, can see illustration here or […]

Leave a Reply