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.