1

I 'm working on a web application. I have my jsp with enctype="multipart/form-data" and when I submit my request, I am unable to get the request parameters in servlet.

The getParameter() calls will all return null. The question is how can overcome this problem?

When it 's not enctyped, this code works fine. I know that this has been asked many times, but I did not find any straight answer

JSP

<form action="upload" method="post" enctype="multipart/form-data">
                <input type="file" name="uploadfile[]" id="uploadfile" size="50" multiple="true" />
                <br/><br/>
                <input type="hidden" name ="e_id" value= <%=userBean.getEid%> />
                <input type="hidden" name ="Uid" value= <%=userBean.getUid()%> />
                <input type="submit" name ="button1" value="Upload" />
            </form>

Servlet

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

    int e_id =0;
    String uid = null;

    HttpSession session1 = request.getSession(true);    
    if(ServletFileUpload.isMultipartContent(request)){//process only if its multipart content
        try 
        {
          List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
          for(FileItem item : multiparts)
          {
              if(!item.isFormField())
              {
                    String name = new File(item.getName()).getName();
                    item.write( new File(UPLOAD_DIRECTORY + File.separator + name));

                    e_id = Integer.parseInt(request.getParameter("e_id"));
                    uid = request.getParameter("Uid");
              }
              else {}
...
D-Lef
  • 1,219
  • 5
  • 14
  • 20
  • The data is hidden in the request `InputStream`. Check [this](http://stackoverflow.com/questions/19374345) out. – Nikos Paraskevopoulos Dec 29 '13 at 16:45
  • It's in that `else {}` block - when `item.isFormField()` – Ian Roberts Dec 29 '13 at 18:19
  • @NikosParaskevopoulos interesting method, but the variable **map** returns only this `Content-Disposition: form-data; name="uploadfile[]"; filename}` and as a result I cannot use `map.get("id")`, which could be a solution to my problem. – D-Lef Dec 31 '13 at 11:23
  • @IanRoberts No it doesn' t work either in the `else{}` block. – D-Lef Dec 31 '13 at 11:25

1 Answers1

0

You need to annotated your servlet with the @MultipartConfig and to get the value of the parameters you use:

Part idPart = req.getPart("e_id");
try (Scanner scanner = new Scanner(idPart.getInputStream())) {
    String idValue = idPart.nextLine(); // read from the part
} 

I have a project in github with an example of how to use it:

Cesar Loachamin
  • 2,740
  • 4
  • 25
  • 33