0

I am uploading a file using HTML form to a Servlet. Generally, I want to upload XML file, but the validation is done on the server side.

How can I get the content of the file as a string on the Servlet?

This is my HTML form:

<form action="xml" enctype="multipart/form-data">
Select XML file: <input data-theme="b" type="file" name="xmlFile" >
<input data-theme="b" id="xml" type="submit" value="Load">
</form>

This is my Servlet:

public class LoadFromXML extends HttpServlet {

    private BlackJackWebService_Service service;
    private BlackJackWebService BlackJackWB;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        URL serverUrl = new URL("http://" + "localhost" + ":" + 8080 + "/bjapi/BlackJackWebService");
        service = new BlackJackWebService_Service(serverUrl);
        BlackJackWB = service.getBlackJackWebServicePort();
        String XMlFileContent = request.getParameter("xmlFile");
        boolean isDuplicate = false;
        boolean isValid = true;
        try {
            BlackJackWB.createGameFromXML(XMlFileContent);
        } catch (DuplicateGameName_Exception ex) {
            isDuplicate = true;
        } catch (InvalidParameters_Exception ex) {
            isValid = false;
        } catch (InvalidXML_Exception ex) {
            isValid = false;
        }
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>BlackJack</title>");
            out.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            out.println("</head>");
            out.println("<body>");
            if (isDuplicate == false && isValid == true) {
                out.println("<h1 id=\"created\">" + " Game created" + "</h1>");
            } else if (isDuplicate == true) {
                out.println("<h1 id=\"created\">" + " Game already exist !" + "</h1>");
            } else if (isValid == false) {
                out.println("<h1 id=\"created\">" + " Invalid XML !" + "</h1>");
            }
            out.println("<form action=\"get_waiting_games\" method=\"get\">");
            out.println("<input data-theme=\"b\" type=\"submit\" value=\"Join a game\">");
            out.println("</form>");
            out.println("<form action=\"create_game.html\" method=\"get\">");
            out.println("<input data-theme=\"b\" type=\"submit\" value=\"Create another game\">");
            out.println("</form>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

Currently, I tried to get the file as a "parameter" - this returns null.

My goal is to upload the file, get its content as a string in the servlet and continue handling the string in the servlet.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Adi Ohana
  • 927
  • 2
  • 13
  • 18
  • 1
    possible duplicate of [How to upload files to server using JSP/Servlet?](http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet) – vanje Jun 19 '14 at 09:40
  • this is for a file. I am looking for the String data of the file – Adi Ohana Jun 19 '14 at 10:02

2 Answers2

1

File Upload follows RFC 1687 and sends a Multipart to the server (multipart/form-data)

To process the multipart server side, use an appropriate library such as Apache Commons FileUpload

Bruno Grieder
  • 28,128
  • 8
  • 69
  • 101
  • I am using multipart/form-data in my HTMl form. – Adi Ohana Jun 19 '14 at 09:57
  • Yes but you are not processing it correctly server side. `request.getParameter()` is **not** the way to go. Check the Commons FileUpload docs – Bruno Grieder Jun 19 '14 at 09:57
  • OK. Now, I am using annotation in my serlvet - @MultipartConfig – Adi Ohana Jun 19 '14 at 09:59
  • and I have this: Part filePart = request.getPart("xmlFile"); InputStream filecontent = filePart.getInputStream(); String XMlFileContent = getStringFromInputStream(filecontent); I stil get 500 internal server error – Adi Ohana Jun 19 '14 at 10:00
  • Catch the exception server side and print the trace to see what triggers the 500 – Bruno Grieder Jun 19 '14 at 10:02
  • יונ 19, 2014 12:55:02 PM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet [LoadFromXML] in context with path [/BlackJackMidServer] threw exception [org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is null] with root cause org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is null – Adi Ohana Jun 19 '14 at 10:03
  • Try `
    ` and re-implement `doPost()`
    – Bruno Grieder Jun 19 '14 at 10:11
  • still same exception on this line of code: Part filePart = request.getPart("xmlFile"); – Adi Ohana Jun 19 '14 at 10:14
  • Strange that your content-type header is null. Any proxy/other soft on the way ? You will need to sniff the request and response. Check what your browser emits using the browser provided developer tools – Bruno Grieder Jun 19 '14 at 10:17
  • Accept:text/html, */*; q=0.01 Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en;q=0.8,he;q=0.6 Connection:keep-alive Content-Length:0 Cookie:JSESSIONID=1B5701E4B673E9278C464AB0B296B5F5 Host:localhost:8080 Origin:http://localhost:8080 Referer:http://localhost:8080/BlackJackMidServer/welcome.html User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 X-Requested-With:XMLHttpRequest – Adi Ohana Jun 19 '14 at 10:19
  • looks like the content header is 0: Content-Length: 0 – Adi Ohana Jun 19 '14 at 10:22
1

You can use commons file upload to parse multipart request. Common file upload gives you a FileItem instance when you are done with request parsing. Fetch the input stream from FileItem instance and use the contents in your servlet.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws  ServletException, IOException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    // Parse the request
    List<FileItem> items = upload.parseRequest(request);
    for (FileItem item : items){
        InputStream in = item.getInputStream();
        //Use in here
    }
}
Mohit
  • 1,740
  • 1
  • 15
  • 19