使用Java Servlet上传文件

时间:2015-12-15 16:07:42

标签: java jsp servlets java-ee

我有一个上传图像的Servlet,并将路径保存在MySQL数据库中。我在不同的jsp页面上使用相同的代码进行另一个图像上传,我在“getFileName();”上得到一个空指针异常

我认为此代码没有任何区别。请帮忙:

  

addlientimage.java

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ClassNotFoundException, SQLException {
        response.setContentType("text/html;charset=UTF-8");

        String name = request.getParameter("clientname");
        String id = request.getParameter("clientid");
        String password = request.getParameter("clientpassword");
        String email = request.getParameter("clientemail");

        final String path = getServletContext().getRealPath("/imgs");
        final Part filePart = request.getPart("imageurl");
        final String fileName = getFileName(filePart);
        String url = "imgs/" + fileName;

        OutputStream outStream;
        outStream = null;
        InputStream filecontent = null;
        final PrintWriter writer = response.getWriter();
        response.sendRedirect("clients.jsp");

        try {
            outStream = new FileOutputStream(new File(path + File.separator
                    + fileName));
            filecontent = filePart.getInputStream();

            int read = 0;
            final byte[] bytes = new byte[1024];

            while ((read = filecontent.read(bytes)) != -1) {
                outStream.write(bytes, 0, read);
            }
            Mysqlconnector dbconnect = new Mysqlconnector();
            /* TODO output your page here. You may use following sample code. */
            try (PreparedStatement clientinfo = dbconnect.getConnection().prepareStatement("INSERT INTO clients VALUES ( ?, ?, ?, ?, ? )")) {
                clientinfo.setString(1, id);
                //setting the first placeholder to the password recieved from the client
                clientinfo.setString(2, password);
                clientinfo.setString(3, name);
                clientinfo.setString(4, url);
                clientinfo.setString(5, email);

                clientinfo.executeUpdate();

                String clients = new PopulateClientsTable().getClientRows();

                HttpSession session = request.getSession();
                session.setAttribute("clients", clients);

            }

        } catch (FileNotFoundException fne) {
            writer.println("You either did not specify a file to upload or are "
                + "trying to upload a file to a protected or nonexistent "
                + "location.");
            writer.println("<br/> ERROR: " + fne.getMessage());

        } finally {
            if (outStream != null) {
                outStream.close();
            }
            if (filecontent != null) {
                filecontent.close();
            }
            if (writer != null) {
                writer.close();
            }
        }
    }

    private String getFileName(final Part part) {
        final String partHeader = part.getHeader("content-disposition");
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(
                        content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }
  

addmanager.java

response.setContentType("text/html;charset=UTF-8");

    String personName = request.getParameter("mediapersonname");
    String productName = request.getParameter("productname");
    String mediainfoid = request.getParameter("mediainfoid");
    String mediaAbout = request.getParameter("mediaabout");
    String personAbout = request.getParameter("personabout");
    String productAbout = request.getParameter("productabout");

    final String path = getServletContext().getRealPath("/imgs");
    final Part filePart = request.getPart("personurl");
    final String fileName = getFileName(filePart);
    String url = "imgs/" + fileName;

    OutputStream outStream;
    outStream = null;
    InputStream filecontent = null;
    final PrintWriter writer = response.getWriter();
    response.sendRedirect("adminmediainfo.jsp");

    try {
        outStream = new FileOutputStream(new File(path + File.separator
                + fileName));
        filecontent = filePart.getInputStream();

        int read = 0;
        final byte[] bytes = new byte[1024];

        while ((read = filecontent.read(bytes)) != -1) {
            outStream.write(bytes, 0, read);
        }

        Mysqlconnector dbconnect = new Mysqlconnector();
        /* TODO output your page here. You may use following sample code. */
        try (PreparedStatement clientinfo = dbconnect.getConnection().prepareStatement("INSERT INTO mediainfo VALUES ( ?, ?, ?, ?, ?, ?, ? )")) {
            //setting the first placeholder to the password recieved from the client
            clientinfo.setString(1, mediainfoid);
            clientinfo.setString(2, mediaAbout);
            clientinfo.setString(3, personName);
            clientinfo.setString(4, productName);
            clientinfo.setString(5, productAbout);
            clientinfo.setString(6, personAbout);
            clientinfo.setString(7, url);

            clientinfo.executeUpdate();

            String clients = new PopulateMediaInfoTable().getClientRows();

            HttpSession session = request.getSession();
            session.setAttribute("mediainfo", clients);

        }

    } catch (FileNotFoundException fne) {
        writer.println("You either did not specify a file to upload or are "
                + "trying to upload a file to a protected or nonexistent "
                + "location.");
        writer.println("<br/> ERROR: " + fne.getMessage());

    } finally {
        if (outStream != null) {
            outStream.close();
        }
        if (filecontent != null) {
            filecontent.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
}

private String getFileName(final Part part) {
    final String partHeader = part.getHeader("content-disposition");
    for (String content : part.getHeader("content-disposition").split(";")) {
        if (content.trim().startsWith("filename")) {
            return content.substring(
                    content.indexOf('=') + 1).trim().replace("\"", "");
        }
    }
    return null;
}

addclientimage.java的代码有效。 addmanager.java的代码没有。

  

错误日志

type Exception report

message

description The server encountered an internal error that prevented it from fulfilling this request.

exception

java.lang.NullPointerException
    AddMediaInfo.getFileName(AddMediaInfo.java:115)
    AddMediaInfo.processRequest(AddMediaInfo.java:53)
    AddMediaInfo.doPost(AddMediaInfo.java:158)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.15 logs.

1 个答案:

答案 0 :(得分:0)

我发现getFileName抛出NPE的原因只有两个:

final String partHeader = part.getHeader("content-disposition");
for (String content : part.getHeader("content-disposition").split(";")) {
  • part为空,因此您必须确保调用方法未将null传递给getFileName。 I.E。:存在一个&#34; personurl&#34;输入请求中的一部分。
  • Wither partHeader为空,因此您必须确保客户端实际上包含&#34;内容处置&#34;已发送请求中的标头。