java用servlet实现文件上传到数据库 2009-03-19 14:26 index.jsp 文件上传 web.xml upload servletUpload upload /servletUpload index.jsp lib:jspupload.jar java: import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; import com.jspsmart.upload.*; public class servletUpload extends HttpServlet { private ServletConfig config; /** * 初始化Servlet */ final public void init(ServletConfig config) throws ServletException { this.config = config; } /** * 处理GET请求 */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println("jspSmartUpload : Servlet Sample"); out.println(""); out.println("The method of the HTML form must be POST."); out.println(""); out.println(""); } /** * 响应POST请求 */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println("Upload File"); out.println(""); // 变量定义 SmartUpload mySmartUpload = new SmartUpload(); String myFileName = ""; //myFileName为带文件后缀 String filename = ""; //filename为不带文件后缀 String fileext = ""; int filesize = 0; //连接数据库 Connection conn = null; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=TestUpload;User=sa;Password=sa"); System.out.println("Success to connect database"); } catch (Exception e) { System.out.println("Fail to connect database"); e.printStackTrace(); } try { // 初始化 mySmartUpload.initialize(config,request,response); // 上载 mySmartUpload.upload(); com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(1); if (!myFile.isMissing()) { int t1; myFileName = myFile.getFileName(); filename = myFileName.substring(0,myFileName.lastIndexOf('.')); t1 = myFileName.lastIndexOf('.')+1; fileext = myFileName.substring(t1,myFileName.length()); filesize = myFile.getSize(); } String trace="c:/"+myFileName; myFile.saveAs(trace,mySmartUpload.SAVE_PHYSICAL); java.io.File file = new java.io.File(trace); java.io.FileInputStream fis = new java.io.FileInputStream(file); String sql="insert into fileinfo values (?,?,?,?)"; PreparedStatement pstmt=conn.prepareStatement(sql); pstmt.setString(1,filename); pstmt.setString(2,fileext); pstmt.setInt(3,filesize); pstmt.setBinaryStream(4,fis,(int)file.length()); pstmt.executeUpdate(); //删除上传的原始文件 java.io.File origFile = new java.io.File("c:\\"+myFileName); if (origFile.isFile() && origFile.exists()) { origFile.delete(); } // 显示处理结果 out.println(filename + "." + fileext + " has been uploaded."); } catch (Exception e){ out.println("Unable to upload the file."); out.println("Error : " + e.toString()); } out.println(""); out.println(""); } }