Sunday, April 3, 2011

download

import java.io.*;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*
* @author saravana
*/
public class download extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String path= request.getParameter("path");
String filename = request.getParameter("file");
//PrintWriter out = response.getWriter();
System.out.println("inside download servlet");
ServletOutputStream myOut= response.getOutputStream();
try {
File f = new File(path+"\\"+filename);


/*if(f.exists())
// System.out.println(f.toString());
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet download</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet download at " + path + "</h1>");
out.println("<h1>Servlet download at " + filename + "</h1>");*/

response.setContentType("application/download");
response.setHeader("Content-Disposition", "attachment; filename= \""+filename+"\"");

FileInputStream fileIn = new FileInputStream(f);

byte[] outputByte = new byte[4096];
while(fileIn.read(outputByte, 0, 4096) != -1){
myOut.write(outputByte, 0, 4096);
}
}catch (IOException ioe){

throw new ServletException(ioe.getMessage( ));

}

finally {
if (myOut != null)
myOut.close( );
if (buf != null)
buf.close( );
}
}
}

0 comments:

Post a Comment