在Servlet中将文件内容作为字符串获取

时间:2014-06-19 09:32:50

标签: java html xml servlets

我正在使用HTML表单将文件上传到Servlet。通常,我想上传XML文件,但验证是在服务器端完成的。

如何在Servlet上将文件内容作为字符串获取?

这是我的HTML表单:

<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>

这是我的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();
        }
    }

目前,我试图将文件作为“参数” - 这将返回null。

我的目标是上传文件,将其内容作为servlet中的字符串获取,并继续处理servlet中的字符串。

2 个答案:

答案 0 :(得分:1)

文件上传遵循RFC 1687并将Multipart发送到服务器(multipart / form-data)

要处理多部分服务器端,请使用适当的库,例如Apache Commons FileUpload

答案 1 :(得分:1)

您可以使用commons文件上传来解析多部分请求。完成请求解析后,公共文件上载会为您提供FileItem实例。从FileItem实例获取输入流并使用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
    }
}