Mysql数据库建表语句:
CREATE TABLE `photo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL,
`image` blob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
//DBClassMysql.java 自己添加mysql的java驱动,要不会报错的
package com.abin.upload.image;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public final class DBClassMysql {
//Mysql
private static String driver="com.mysql.jdbc.Driver";
private static String url="jdbc:mysql://localhost:3306/test";
private static String user="root";
private static String password="";
public DBClassMysql ()throws ClassNotFoundException{
}
//Mysql
public static Connection getMysql(){
Connection conn=null;
try{
if(null==conn||conn.isClosed()){
Class.forName(driver).newInstance();
conn=DriverManager.getConnection(url,user,password);
}
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}
return conn;
}
}
//ImageServlet.java 保存文件流的servlet
package com.abin.upload.image;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class ImageServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
super.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection conn = null;
PreparedStatement ps=null;
String title = null;
int imageLength = 0;
byte[] buffer = new byte[imageLength];
InputStream in = null;
int total = 0;
int once = 0;
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload file = new ServletFileUpload(factory);
try {
List lst = file.parseRequest(request);
Iterator it = lst.iterator();
while (it.hasNext()) {
FileItem fileItem = (FileItem) it.next();
if (fileItem.isFormField()) {
title = fileItem.getString("UTF-8");
System.out.println("表单数据的名称是:" + fileItem.getFieldName()
+ ":表单的内容是:" + fileItem.getString("UTF-8"));
} else {
if (fileItem.getName() != null
&& !fileItem.getName().equals("")) {
imageLength = Integer.parseInt(String.valueOf(fileItem
.getSize()));
in = fileItem.getInputStream();
System.out.println("上传文件的名称:" + fileItem.getName());
System.out.println("上传文件的大小:" + fileItem.getSize());
System.out.println("上传文件的类型:"
+ fileItem.getContentType());
System.out.println("上传文件的类型:"
+ fileItem.getInputStream());
}
String sql="insert into photo (title,image) values (?,?)";
conn=DBClassMysql.getMysql();
ps=conn.prepareStatement(sql);
ps.setString(1, title);
ps.setBinaryStream(2, in,in.available());
ps.executeUpdate();
}
}
request.getSession().setAttribute("message", "operate success.");
request.getRequestDispatcher("message.jsp").forward(request, response);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
try {
if(ps!=null){
ps.close();
}
if(conn!=null){
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void destroy() {
super.destroy();
}
}
//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>com.abin.upload.image.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/ImageServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
//message.jsp WebRoot下面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>servlet upload</title>
</head>
<body>
<%=session.getAttribute("message") %>
</body>
</html>
//index.jsp WebRoot下面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>servlet upload</title>
</head>
<body>
<form method="post" action="ImageServlet" enctype="multipart/form-data">
标题:<br/>
<input name="title" type="text" /><br/>
请选择您要上传的图片:<br/>
<input name="myimage" type="file" /><br/>
<input type="submit" value="提交" />
<input type="reset" value="重置" />
</form>
</body>
</html>