【发布时间】:2014-03-21 04:51:41
【问题描述】:
我正在尝试将文件从 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>       
<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 条件”作为输出。
【问题讨论】:
-
这不是一个好主意。 JSP 中的 Scriptlet 代码在 1999 年过时了。不要这样做。调试器会快速告诉你哪里出错了。
-
为什么要重新发明轮子?网上有很多例子。例如,参见corejavaexample.blogspot.fr/2013/04/…,您会看到如何处理“multipart/form-data