martes, 20 de septiembre de 2011

Servlet para descargar archivos

Dejo a disposición como utilizar un servlet para descargar archivos.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* A simple Servlet to download a file.
* @author gabriel.solano
*
*/
public class DownloadServlet extends HttpServlet{

private static final long serialVersionUID = 4440011247408877539L;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
downloadFile(resp,
this.getServletContext().getRealPath("/WEB-INF/myFile.pdf"));
}

protected void downloadFile(HttpServletResponse response, String filePath)
throws ServletException, IOException {

File fileToDownload = new File(filePath);
FileInputStream fileInputStream = new FileInputStream(fileToDownload);

ServletOutputStream out = response.getOutputStream();
String mimeType = new MimetypesFileTypeMap().getContentType(filePath);

response.setContentType(mimeType);
response.setContentLength(fileInputStream.available());
response.setHeader( "Content-Disposition", "attachment; filename=\""
+ fileToDownload.getName() + "\"" );

int c;
while((c=fileInputStream.read()) != -1){
out.write(c);
}
out.flush();
out.close();
fileInputStream.close();
}
}

2 comentarios:

  1. A null Pointer Exception in the line 30 es generated

    ResponderEliminar
    Respuestas
    1. I'm sorry:
      The files are saved in the sheet WEB-inf of the project.

      Thank you.

      Eliminar