我正在尝试从Apache7.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 cannot if condition“作为输出。
发布于 2014-02-20 18:46:37
为了回答实际问题,你得到一个空返回值的原因有两个。首先,代码:
String str=request.getParameter("file");
Part filePart=request.getPart(str);应该只是简单地
Part filePart = request.getPart("file");但是,至关重要的是,request.getPart方法是Servlet3.0的一个特性,它需要使用带有@MultipartConfig注释的Servlet (而不是JSP文件)。
然而,代码中充斥着糟糕的实践。
正如评论中所述,十多年来一直不鼓励使用scriptlet;您应该首先将servlet用作某种控制器,然后使用以下内容(在内部)将其转发到JSP视图:
request.getRequestDispatcher("/WEB-INF/jsp/view.jsp").forward(request, response);<font>和<center>超文本标记语言元素也已被弃用多年。
最后,有许多库可以帮助您上传文件。例如,Apache Commons FileUpload。
如何将上述所有内容放在一起的Here is a good example。
https://stackoverflow.com/questions/21904528
复制相似问题