0

Maybe my question is redundant with this one, but I can't find out how to handle a multipart HTTP request.

I wrote an HTTP request which use POST to send a file and a string. How to obtain both on server side in my Servlet ?

Here is what I did. Am I on the right way ?

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Gson gson = new Gson();
    Status status = new Status();

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if(isMultipart){
        status.setSuccess(true);
        status.setDescription("It is OK.");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(MAX_MEMORY_SIZED);
        factory.setRepository(new File(ADRESS_WHERE_I_WANT_TO_PUT_THE_FILE));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(MAX_FILE_SIZE_TO_BE_UPLOADED);
        try {
            List<FileItem> items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) { 

            ... // WHAT TO DO HERE TO GET MY STRING AND MY FILE ???

            }
    }
    else{
        status.setSuccess(false);
        status.setDescription("Not multipart.");
    }
    response.setContentType("application/json;charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    PrintWriter output = response.getWriter();
    output.write(gson.toJson(status));
    output.flush();
}
Community
  • 1
  • 1
cleroo
  • 1,145
  • 2
  • 11
  • 17

1 Answers1

0

I would check out the MultipartParser available at servlets.com

From the website:

There's no sense in reinventing the wheel--here are some servlet support classes I wrote that you can use. Most famous is the file upload package MultipartRequest and MultipartParser

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440