我需要使用servlet处理文件上传,如下所示:
package com.limrasoft.image.servlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.sql.*;
@WebServlet(name="serv1",value="/s1")
public class Account extends HttpServlet{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connecection con=null;
try{
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sajid");
PrintWriter pw=res.getWriter();
res.setContentType("text/html");
String s1=req.getParameter("un");
string s2=req.getParameter("pwd");
String s3=req.getParameter("g");
String s4=req.getParameter("uf");
PreparedStatement ps=con.prepareStatement("insert into account(?,?,?,?)");
ps.setString(1,s1);
ps.setString(2,s2);
ps.setString(3,s3);
File file=new File("+s4+");
FileInputStream fis=new FileInputStream(fis);
int len=(int)file.length();
ps.setBinaryStream(4,fis,len);
int c=ps.executeUpdate();
if(c==0){pw.println("<h1>Registratin fail");}
else{pw.println("<h1>Registration fail");}
}
finally{if(con!=null)con.close();}
}
catch(ClassNotFoundException ce){pw.println("<h1>Registration Fail");}
catch(SQLException se){pw.println("<h1>Registration Fail");}
pw.flush();
pw.close();
}
}
但这会导致错误页面:
HTTP状态500-Servlet3.java(系统找不到指定的文件)
这是怎么引起的,我该如何解决?
最佳答案
您似乎无处可从HTTP请求中提取上载的文件内容。您只在收集文件名,并在相对于服务器当前工作目录的路径上围绕它构建new File()
。我不确定您在编写此代码时的想法,但是当webbrowser在与Web服务器不同的计算机上运行时,仅传递文件名将永远无法工作,因为它们不会共享同一本地磁盘文件系统。
相反,您应该在请求中传递整个文件内容。您可以通过在HTML表单上使用multipart/form-data
编码来实现。
<form action="s1" method="post" enctype="multipart/form-data">
现在,用
@MultipartConfig
注释servlet以启用multipart/form-data
支持。@WebServlet("/s1")
@MultipartConfig
public class Account extends HttpServlet {
然后,要提取上载的文件,只需使用
HttpServletRequest#getPart()
。Part s4 = req.getPart("uf");
文件内容是
InputStream
可用的Part#getInputStream()
。因此,以下所有代码String s4=req.getParameter("uf");
// ...
File file=new File("+s4+");
FileInputStream fis=new FileInputStream(fis);
int len=(int)file.length();
ps.setBinaryStream(4,fis,len);
应该由
Part s4 = req.getPart("uf");
// ...
ps.setBinaryStream(4, s4.getInputStream());
也可以看看:
How to upload files to server using JSP/Servlet?