ITeye博客

上传文件到Mysql数据库

love4J · 2009-11-20 17:34 · SQL · JDBC · MySQL · JSP · Servlet · Markdown

First, you need a table in database. Below is the table script: [code="java"] CREATE TABLE `image` ( `Id` int(11) NOT NULL auto_increment, `Image` blob, PRIMARY KEY (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 [/code] Second,you need a jsp. Below is the HTML block in jsp file: [code="java"]

[/code] Third, you need a servlet to deal with the file upload. Below is the configuration in web.xml and code: [code="java"] TestUploadImageToDB com.TestUploadImageToDB TestUploadImageToDB /TestUploadImageToDB [/code] [code="java"] public class TestUploadImageToDB extends HttpServlet { private static final long serialVersionUID = 6397853149875034008L; public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024*1024); factory.setRepository(new File("c:\\temp")); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(100 * 1024 * 1024); List items = new ArrayList(); try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); System.out.println(name + ":" + value); } else { writeToDB(item.getInputStream()); } } } response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("success!"); out.flush(); out.close(); } public void writeToDB(InputStream ism){ Connection con = null; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); String URL = "jdbc:mysql://localhost:3306/test?user=root&password=root"; con = DriverManager.getConnection(URL); PreparedStatement st = null; InputStream in = new BufferedInputStream(ism); String sql = "insert into image(Image) values(?)"; st = con.prepareStatement(sql); st.setBinaryStream(1, in); int i = st.executeUpdate(); System.out.println("==>" + i); in.close(); }catch(Exception e){ e.printStackTrace(); } finally { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } } [/code]

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。