0

I am trying to create a multi-file upload servlet. I have 1 jsp page which allows user to select multiple files for upload. On clicking the "Upload" button "UploadServlet" is called which is using "Apache Commons" library for uploading the files on server. Below is the code for my JSP & Servlet.

JSP Code:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
    <!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=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
                <form method="post" action="UploadServlet" enctype="multipart/form-data">
                    Select file to upload: <input type="file" name="uploadFile" /><br/>
                    Select file to upload: <input type="file" name="uploadFile2" /><br/>
                    Select file to upload: <input type="file" name="uploadFile3" /><br/>
                    Select file to upload: <input type="file" name="uploadFile4" /><br/>
                <br/><br/>
                <input type="submit" value="Upload" />
                </form>
    </body>
    </html>

Servlet Code:

package org.server.download;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
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;
/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String UPLOAD_DIRECTORY = "upload";
    private static final int THRESHOLD_SIZE     = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 250; // 250MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 300; // 3000MB
    /**
     * Default constructor. 
     */
    public UploadServlet() {
        // 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
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //PrintWriter writer = response.getWriter();
        //writer.println("Request does not contain upload data");
        if (!ServletFileUpload.isMultipartContent(request)) {
            PrintWriter writer = response.getWriter();
            writer.println("Request does not contain upload data");
            writer.flush();
            return;
        }

        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(THRESHOLD_SIZE);
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // constructs the directory path to store upload file
        String uploadPath = getServletContext().getRealPath("")
            + File.separator + UPLOAD_DIRECTORY;
        // creates the directory if it does not exist
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        try {
            // parses the request's content to extract file data
            List formItems = upload.parseRequest(request);
            Iterator iter = formItems.iterator();

            // iterates over form's fields
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);
                    // saves the file on disk
                    item.write(storeFile);
                }
            }
            request.setAttribute("message", "Upload has been done successfully!");
        } catch (Exception ex) {
            request.setAttribute("message", "There was an error: " + ex.getMessage());
        }
        getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);

    }

}

I run the application as below:

enter image description here

After clicking the Upload button. I get the below exception:

enter image description here

Although files are getting uploaded. But I don't know why is this exception coming. Can anyone pls help?

Jahar tyagi
  • 91
  • 13
  • Access denied when uploading files often means that the user that runs the server process doen't have write access to the designed upload folder – Raffaele Mar 01 '16 at 13:39
  • Files are being uploaded when I check the designated folder. I have checked the user permission too on that particular folder but it still throws the same exception. – Jahar tyagi Mar 01 '16 at 14:01
  • Can anyone please help me to resolve this. – Jahar tyagi Mar 02 '16 at 06:00
  • The duplicate answers your technical problem (getRealPath == bad, bad, bad!). I would only like to remark that the Apache Commons FileUpload approach is completely outdated as it is unnecessary since Servlet 3.0 (since 2009 thus!). It's since then simply already built into the servletcontainer itself. See also http://stackoverflow.com/q/2422468 – BalusC Mar 02 '16 at 08:29

0 Answers0