Apache Commons FileUpload and Download

JSP Page containing html FileUpload component and link for dowloading that document. Two jars are required : commons-fileupload.jar and commons-io.jar

index.jsp

<%-- 
    Document   : index
    Created on : Feb 24, 2011, 12:46:27 PM
    Author     : TaherT
--%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>File Upload Download through common apache</title>
    </head>
    <body>
        <form  id="frmUploadDoc" method="post" action="<%=request.getContextPath()%>/FileUpload?action=upload" enctype="multipart/form-data" name="frmUploadDoc">
            <table width="100%" cellspacing="0" class="tableList_1 t_space">
                <tr>
                    <td class="ff" width="15%"> Select Document   : <span class="mandatory">*</span></td>
                    <td width="85%">
                        <input name="uploadDocFile" id="uploadDocFile" type="file" class="formTxtBox_1" style="width:450px; background:none;"/><br/>
                    </td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td>
                        <label class="formBtn_1" id="lbUpload">
                            <input type="submit" name="upload" id="btnUpload" value="Upload"/>
                        </label>
                    </td>
                </tr>
            </table>
        </form>
        <br/>
        <table width="100%" cellspacing="0" class="tableList_1 t_space" border="5">
            <tr>
                <th align="center">S. No.</th>
                <th align="center">Document Name</th>
                <th align="center">File Size</th>
                <th align="center">Action</th>
            </tr>
            <tr>
                <td align="center">1</td>
                <td align="center">content.txt</td>
                <td align="center">3858</td>
                <td align="center">
                    <a href="<%=request.getContextPath()%>/FileUpload?action=download&docName=content.txt&docSize=3858" title="Download"><img src="../resources/images/Dashboard/downloadIcn.png" alt="Download" /></a>
                </td>
            </tr>
        </table>
    </body>
</html>

FileUploadServlet.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package files;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet(name = "FileUpload", urlPatterns = {"/FileUpload"})
public class FileUpload extends HttpServlet {

    private static final String TMP_DIR_PATH = "c:\\tmp";
    private File tmpDir;
    private File destinationDir;
    DataInputStream dis = null;
    BufferedInputStream bis = null;
    FileInputStream fis = null;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        tmpDir = new File(TMP_DIR_PATH);
        if (!tmpDir.isDirectory()) {
            tmpDir.mkdir();
        }
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String action = request.getParameter("action");
        try {
            if (action.equals("upload")) {
                String DESTINATION_DIR_PATH = "C:/Test";
                String realPath = DESTINATION_DIR_PATH;
                System.out.println("Real Path " + realPath);
                destinationDir = new File(realPath);
                if (!destinationDir.isDirectory()) {
                    destinationDir.mkdir();
                }
                response.setContentType("text/html");
                try {
                    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

                    fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB

                    fileItemFactory.setRepository(tmpDir);

                    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
                    try {

                        List items = uploadHandler.parseRequest(request);
                        Iterator itr = items.iterator();
                        while (itr.hasNext()) {
                            FileItem item = (FileItem) itr.next();
                            if (item.isFormField()) {
                                System.out.println("Field Name = " + item.getFieldName() + ",Field Value = " + item.getString());
                            } else {
                                System.out.println(
                                        "File Name = " + item.getName()
                                        + ", Content type = " + item.getContentType()
                                        + ", File Size = " + item.getSize());
                                String fileName = "";
                                if (item.getName().lastIndexOf("\\") != -1) {
                                    fileName = item.getName().substring(item.getName().lastIndexOf("\\") + 1, item.getName().length());
                                } else {
                                    fileName = item.getName();
                                }

                                File file = new File(destinationDir, fileName);
                                item.write(file);
                                response.sendRedirect("index.jsp");
                            }
                        }
                    } catch (Exception e) {
                    }

                } catch (Exception e) {
                    System.out.println(e);
                }
            } else if (action.equals("download")) {
                String pathName = "C:/Test";
                String docName = request.getParameter("docName");
                String docSize = request.getParameter("docSize");
                File file = new File(pathName+"\\"+docName);
                fis = new FileInputStream(file);
                byte[] buf = new byte[Integer.valueOf(docSize)];
                int offset = 0;
                int numRead = 0;
                while ((offset < buf.length)
                        && ((numRead = fis.read(buf, offset, buf.length - offset)) >= 0)) {

                    offset += numRead;

                }
                fis.close();
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;filename=" + docName+"");
                ServletOutputStream outputStream =  response.getOutputStream();
                outputStream.write(buf);
                outputStream.flush();
                outputStream.close();
            }
        } finally {
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}

Output :

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

7 Responses to Apache Commons FileUpload and Download

  1. madupiz says:

    Was very helpful ,
    Thank you.

  2. sdfldkfjl says:

    thanx Alooooooooooooooooooooooooooooooooooooooooooooooooot love you 🙂

  3. Surendra says:

    i want upload files from client system to server file system by using *JSF* Can you Help me

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s