user3661334
user3661334

Reputation: 85

J2EE : how to download a file?

I have currently a JSP page with a list of files and I would like download each file by a click on this name in the list. My JSP code :

    <c:forEach var="listFiles" items="${listFiles}" varStatus="status">
       <span id="file-${status.index}" class="files">
           <a href="Download">
              <c:out value="${listFiles[status.index]}"></c:out>
           </a>
    </c:forEach>

I found a function for my servlet which run but it's a simple example where we give the path file to the servlet and I would I want this code be generic. How to give each path file to the servlet ?

Upvotes: 0

Views: 4294

Answers (1)

Darshan Patel
Darshan Patel

Reputation: 2899

Put this code in your servlet :

String filename=null;

try
{
    filename = request.getParameter("filename");        

    if(filename == null || filename.equals(""))
    {
        throw new ServletException("File Name can't be null or empty");
    }

    String filepath = "yourDirPath"+filename;   //change your directory path

    File file = new File(filepath);
    if(!file.exists())
    {
        throw new ServletException("File doesn't exists on server.");
    }

    response.setContentType("APPLICATION/OCTET-STREAM");
    response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\""); 

    java.io.FileInputStream fileInputStream = new java.io.FileInputStream(filepath);

    int i; 
    while ((i=fileInputStream.read()) != -1) 
    {
         response.getWriter().write(i); 
    } 
    fileInputStream.close();
}
catch(Exception e)
{
    System.err.println("Error while downloading file["+filename+"]"+e);
}

Lets say your servlet url-pattern is : download

Now, your html code for downloading file should be something like this :

<a href="download?filename=YourFileName" target="_blank">Click here to download file</a>

Upvotes: 3

Related Questions