【问题标题】:get file content as a string in Servlet在 Servlet 中将文件内容作为字符串获取
【发布时间】:2014-08-09 19:10:47
【问题描述】:

我正在使用 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 中的字符串。

【问题讨论】:

标签: java html xml servlets


【解决方案1】:

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

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

【讨论】:

  • 我在我的 HTMl 表单中使用 multipart/form-data。
  • 是的,但您没有在服务器端正确处理它。 request.getParameter()不是要走的路。检查 Commons FileUpload 文档
  • 好的。现在,我在我的 serlvet 中使用注释 - @MultipartConfig
  • 我有这个:Part filePart = request.getPart("xmlFile"); InputStream 文件内容 = filePart.getInputStream();字符串 XMlFileContent = getStringFromInputStream(filecontent);我仍然收到 500 内部服务器错误
  • 捕获异常服务器端并打印跟踪以查看触发 500 的原因
【解决方案2】:

您可以使用公共文件上传来解析多部分请求。完成请求解析后,通用文件上传会为您提供一个 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
    }
}

【讨论】:

猜你喜欢
  • 2013-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-31
  • 2014-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多