Return a file with a Servlet

Here is some sample java code.
This code returns a file from a Servlet:

package com.javaoracleblog.servlets;
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
/**  * Servlet to download text to a file.  *  * @author Edwin Korsten  * @version 1.0  */ public class Download extends HttpServlet {
 /**   * Return the contents of the requested file.   */  public void doGet(HttpServletRequest request, HttpServletResponse response)    throws IOException, ServletException {   PrintWriter out = null;   try {
   String fileName = "test.txt";    response.setContentType("application/x-msdownload");    response.addHeader("Content-disposition", "attachment; filename=\""      + fileName + "\"");    out = response.getWriter();    out.write("This is the contents of the file");   } catch (Exception e) {    if (out == null) {     response.setContentType("text/html");     out = response.getWriter();    }    out.write("”      + “Error trying to get file : “);    out.write(e.toString());    out.write(”");   }   out.close();  }
 public void doPost(HttpServletRequest request, HttpServletResponse response)    throws IOException, ServletException {   doGet(request, response);  }
}

Leave a Reply

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