0

I am trying to get the values from a multipart form using Parts, without using DiskFileItemFactory. In this code I'm able to process the file, but not sure how to obtain the other non-file values passed.

/**
 * Directory where uploaded files will be saved, its relative to
 * the web application directory.
 */
private static final String UPLOAD_DIR = "uploads";

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // gets absolute path of the web application
    String applicationPath = request.getServletContext().getRealPath("");
    // constructs path of the directory to save uploaded file
    String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;

    // creates the save directory if it does not exists
    File fileSaveDir = new File(uploadFilePath);
    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdirs();
    }
    System.out.println("Upload File Directory="+fileSaveDir.getAbsolutePath());

    String fileName = null;
    //Get all the parts from request and write it to the file on server
    for (Part part : request.getParts()) {
        fileName = getFileName(part);
        part.write(uploadFilePath + File.separator + fileName);
    }

    request.setAttribute("message", fileName + " File uploaded successfully!");
    getServletContext().getRequestDispatcher("/response.jsp").forward(
            request, response);
}

/**
 * Utility method to get file name from HTTP header content-disposition
 */
private String getFileName(Part part) {
    String contentDisp = part.getHeader("content-disposition");
    System.out.println("content-disposition header= "+contentDisp);
    String[] tokens = contentDisp.split(";");
    for (String token : tokens) {
        if (token.trim().startsWith("filename")) {
            return token.substring(token.indexOf("=") + 2, token.length()-1);
        }
    }
    return "";
}

}

MissXToTheT
  • 39
  • 1
  • 8

2 Answers2

0

Please find below:

    @WebServlet(name = "ImageHandler", urlPatterns = {"/ImageHandler"})
@MultipartConfig(maxFileSize = 100 * 1024 * 1024)  // 100MB max
public class ImageHandler extends HttpServlet {

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

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String name = request.getParameter("name");
        out.println("<br>name: " + name);

        // Create a new file upload handler
        InputStream inputStream = null;

        // obtains the upload file part in this multipart request
        Part filePart = request.getPart("file");

        if (filePart != null) {
            // prints out some information for debugging
            out.println("<br>getName: " + filePart.getName());
            out.println("<br>getSize: " + filePart.getSize());
            out.println("<br>getContentType: " + filePart.getContentType());

            // obtains input stream of the upload file
            //inputStream = filePart.getInputStream();
        }
    }

}

Html Form:

<form action="ImageHandler" method="post" enctype="multipart/form-data" role="form">
            Name: <input  maxlength="100" type="text" name="name" class="form-control" placeholder=""  />

            <br>
                file: <input type="file" id="files"  name="file" /> 
            <br>

            <input type="submit" value="submit">
        </form>
ErShakirAnsari
  • 653
  • 7
  • 19
0

First approach

//Read the parameters as follows
request.getParameter("name");

//Read the file as follows
Part filePart = request.getPart("fileParam");

Second approach

HttpServletRequestWrapper requestWrapper = (HttpServletRequestWrapper) request;

//Read the parameters
Enumeration<String> parameterNames = requestWrapper.getRequest().getParameterNames();
while (parameterNames.hasMoreElements()) {
  String paramKey = (String) parameterNames.nextElement();
}

//Read the multiple files
List<Part> fileParts = request.getParts().stream().filter(part -> <<fileParam>>.equals(part.getName())).collect(Collectors.toList());