Here is small piece of java code to generate binary stream which tells browser to save file as attachment. I believe that this code will help java beginners to understand HttpServletResponse of the Servlets.
Read More: http://commons.apache.org/fileupload/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
package com.gaurangjadia.code.controllers; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Download extends HttpServlet { private static final long serialVersionUID = 1L; public Download() { super(); } public void init(ServletConfig config) throws ServletException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try{ String fileName = request.getParameter("name"); String path = request.getSession().getServletContext().getRealPath("/WEB-INF/upload/"); //strFileName: Name of the file which is being downloaded and which exist under /WEB-INF/upload/ path if(fileName.equals("strFileName")){ path += "/" + fileName; File file = new File(path); Integer intFileLength = (int)(file.length() / 1024) + 1; response.setContentType(new MimetypesFileTypeMap().getContentType(file)); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); FileInputStream in = new FileInputStream(path); OutputStream out = response.getOutputStream(); byte buf[] = new byte[intFileLength]; int bytesRead = 0; while( (bytesRead = in.read(buf)) > 0 ){ out.write(buf, 0, bytesRead); } out.close(); in.close(); } else{ request.getRequestDispatcher("/WEB-INF/download.jsp").forward(request, response); } } catch(Exception ex){ request.getRequestDispatcher("/WEB-INF/download.jsp").forward(request, response); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } |