Showing posts with label server. Show all posts
Showing posts with label server. Show all posts

Saturday, November 10, 2012

Java code to list files and download files using jsp and servlet


Here is code that will read a file from a directory. Once clicked, the files will be downloaded.

The files are stored in a directory - D:/filesFolder/
Modify the path, as per your file path in  DownloadFile and in .jsp
--------------------------------------------------------------------------------------

The servlet java file is DownloadFile.java
--------------------------------------------------------------------------------------


package com.sandeepshabd.example;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DownloadFile
 */
public class DownloadFile extends HttpServlet implements
javax.servlet.Servlet{
private static final long serialVersionUID = 1L;
private static final int BUFSIZE = 4096;
    /**
     * Default constructor.
     */
    public DownloadFile() {
        // 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 name = request.getParameter("fileName");
if(name==null || name.length()==0)
{
//DO NOTHING
}else
{
startDownload(response,name);
}
}



void startDownload(HttpServletResponse response,String name)
{

String filePath = "D://filesFolder//"+name;
File file = new File(filePath);
        int length   = 0;
        ServletOutputStream outStream;
try {
outStream = response.getOutputStream();

       ServletContext context  = getServletConfig().getServletContext();
       String mimetype = context.getMimeType(filePath);
     
       // sets response content type
       if (mimetype == null) {
           mimetype = "application/octet-stream";
       }
       response.setContentType(mimetype);
       response.setContentLength((int)file.length());
       String fileName = (new File(filePath)).getName();
     
       // sets HTTP header
       response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
     
       byte[] byteBuffer = new byte[BUFSIZE];
       DataInputStream in;
try {
in = new DataInputStream(new FileInputStream(file));        // reads the file's bytes and writes them to the response stream
       try {
while ((in != null) && ((length = in.read(byteBuffer)) != -1))
{
   outStream.write(byteBuffer,0,length);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
     
       in.close();
       outStream.close();
     
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

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

}


---------------------------------- files.jsp under webcontent---------------------------------------------

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
Skunkwork Download File

Directories

    <%
    String root="D://filesFolder//";
    java.io.File file;
    java.io.File dir = new java.io.File(root);

    String[] list = dir.list();

    if (list.length > 0) {

    for (int i = 0; i < list.length; i++) {
      file = new java.io.File(root + list[i]);
      if (file!= null && !file.isDirectory() ) {
      %>
      <%
         }
      }
    }
    %>
    ----------------------------------------------------------------------------------