How to download file from a folder using Java
In this article we are going to see how to download a file from a folder using Java, In addition to that we are also going to see how to change the format of that file and download it.

JSP:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <a href="download">Download</a>
    </body>
</html>

Servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/plain");

        
         response.setHeader("Content-disposition","attachment; filename=check.doc"); // Used to name the download file and its format

         File my_file = new File("E://outputtext.txt"); // We are downloading .txt file, in the format of doc with name check - check.doc

         
         OutputStream out = response.getOutputStream();
         FileInputStream in = new FileInputStream(my_file);
         byte[] buffer = new byte[4096];
         int length;
         while ((length = in.read(buffer)) > 0){
            out.write(buffer, 0, length);
         }
         in.close();
         out.flush();
    }

This code will do for downloading a file from path, This code will also work if you have saved your path in database and to download from that path.

We will see about  downloading the file from the path saved in database in next article

 

By Sri

Leave a Reply

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