什么JAR包含getPart()方法?

时间:2014-02-20 10:09:50

标签: java mysql jsp

我正在尝试从apache 7.0服务器上传文件到mySQL数据库。我已经编写了html代码来上传文件。

<form action="UploadValidate.jsp" method="post" enctype="multipart/form-data">
    <fieldset>
    <legend><font size="4" color="white">File Upload</font></legend><br/><br/>
    <font size="4" color="white"><b>
    <h3> Select File to Upload</h3> &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    <input type="file"name="file" /><br/><br/>

    <center>
    <input type="submit" value="Upload File" /><br/><br/></center>

    </font>
    </fieldset>
</form>

这是UploadValidate.jsp

      <%@ page import="java.io.*,java.sql.*,java.lang.String.*,com.oreilly.servlet.*"%>
      <%
       InputStream inputstream=null;
       String str=request.getParameter("file");
       Part filePart=request.getPart(str);
       out.println(filePart);
       if(filePart!=null){
           out.println(filePart.getName());
           out.println(filePart.getSize());
           out.println(filePart.getContentType());
           //output the inputstream of uploaded file
           inputstream=filePart.getInputStream();
        }
       else{
       out.println("cannot execute if condition");
        }
      %>
     <%
    try{
    String message=null;
    int id=123;
    String url="jdbc:mysql://localhost:3306/Project";
    Class.forName("com.mysql.jdbc.Driver");
    Connection con=DriverManager.getConnection(url,"root","admin");
    String sql="INSERT INTO uploadfile(id,file) VALUES(?,?)";
    PreparedStatement stmt=con.prepareStatement(sql);
    stmt.setInt(1,id);
    if(inputstream!=null){
        stmt.setBlob(2,inputstream);
    }
    int row=stmt.executeUpdate();
    if(row>0){
        out.print("<h3><font color=red> Success Welcome!!!!!<br><br> </font></h3>");
    }
}catch(Exception e){
    e.printStackTrace();
}
//session.setAttribute("Message",message);
//response.sendRedirect("Message.jsp");
   %>

当我选择要上传的文件时,filePart对象返回null。如果bolck并返回它会终止                        “null不能执行if condition”作为输出。

1 个答案:

答案 0 :(得分:3)

要回答实际问题,获得空返回值的原因是双重的。首先,代码:

   String str=request.getParameter("file");
   Part filePart=request.getPart(str);

应该只是

   Part filePart = request.getPart("file");

但是,至关重要的是,request.getPart方法是一个Servlet 3.0特性,它需要使用带有@MultipartConfig注释的servlet(而不是JSP文件)。

然而,代码充斥着不好的做法。

正如评论中所述,十多年来一直不鼓励使用scriptlet;您应首先使用servlet作为某种控制器,然后使用以下内容将(内部)转发到JSP视图:

request.getRequestDispatcher("/WEB-INF/jsp/view.jsp").forward(request, response);

<font><center> HTML元素也已弃用多年。

最后,有很多库可以帮助处理文件上传。例如,Apache Commons FileUpload

Here is a good example如何将上述所有内容放在一起。