我想从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>       
<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不能执行条件”作为输出。
这不是一个好主意。 JSP中的Scriptlet代码在1999年过时了。不要这样做。一个调试器会很快显示你错误的地方。 – duffymo
你为什么重新发明轮子?他网络上有很多例子。例如,请参见http://corejavaexample.blogspot.fr/2013/04/how-to-upload-file-in-jsp.html,您将看到如何处理“multipart/form-data – StephaneM