2014-02-20 36 views
1

我想从apache 7.0服务器上传一个文件到mySQL数据库。我已经写了HTML代码来上传文件。JAR包含getPart()方法?

<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对象返回空eventhough我已选择要上传的文件。它终止,如果bolck并返回 “null不能执行条件”作为输出。

+2

这不是一个好主意。 JSP中的Scriptlet代码在1999年过时了。不要这样做。一个调试器会很快显示你错误的地方。 – duffymo

+0

你为什么重新发明轮子?他网络上有很多例子。例如,请参见http://corejavaexample.blogspot.fr/2013/04/how-to-upload-file-in-jsp.html,您将看到如何处理“multipart/form-data – StephaneM

回答

3

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

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

应该简单地

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

但是,关键的是,该request.getPart方法是一个Servlet 3.0功能,它需要使用用@MultipartConfig注释一个servlet(未JSP文件)的。

但是,代码中散布着糟糕的做法。

正如评论中所述,使用scriptlets已经被阻止了十多年;

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

<font><center> HTML元素也被废弃了多年:你应该使用像第一次使用servlet作为某种控制器,再往前(内部)到你的JSP视图。

最后,还有许多库来帮助文件上传。例如,Apache Commons FileUpload

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

+0

我曾尝试使用Part filePart = request.getPart(“file”); 我无法得到结果,它返回null – Varun

+0

我编辑了我的答案,以解释为什么'request.getPart(“file”)'也不起作用。真的需要将代码从JSP中移出并存入Servlet中,如果您真的想将它保存在JSP中,那么您需要使用Apache Commons FileUpload来处理上载。 – megaflop

+0

谢谢。 – Varun