How to create Download File button using Java Servlets

Before you read this post i would recommend you to go through these earlier post to understand what we did and what we are going to do.

Convert SVG to PNG using Java Servlet

How to use Java Servlets and Ajax

I would tell you what we did in earlier post. We converted SVG to PNG and stored on the server. Now i want to have a download image button on my page so that users can download it on their machine rather than tricks like “Ctrl+S”.

So for this purpose i will create a new Java Servlet and call it download.java

On my index.jsp i will have a download button that will send the image name to download.java and it will do the rest. I will send image name with the URL, so i will write my code in doGet method.

1) A simple download button on index.jsp (i am hard coding the image name, but you can program it as well)

<a href='download?img=final.png'>Download file</a>

2) download.java

/**
 * Servlet implementation class saveimage
 */
@WebServlet({ "/saveimage", "/saveimage/*" })
public class saveimage extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final int BYTES_DOWNLOAD = 1024;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public saveimage() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String img_name = request.getParameter("img");

		// Set the headers.
		response.setContentType("application/x-download");
		response.setHeader("Content-Disposition", "attachment; filename=" + img_name);

		InputStream URI_input = getServletContext().getResourceAsStream("assets/output/" + img_name);

		int read=0;
		byte[] bytes = new byte[BYTES_DOWNLOAD];
		OutputStream os = response.getOutputStream();

		while((read = URI_input.read(bytes))!= -1){
			os.write(bytes, 0, read);
		}
		os.flush();
		os.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

So, now after user will click on "Download File" link a popup will be there to save image anywhere on their machine.

Keep checking for more tutorials.
Tags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*