First, you need a table in database. Below is the table script:
Second,you need a jsp. Below is the HTML block in jsp file:
Third, you need a servlet to deal with the file upload. Below is the configuration in web.xml and code:
CREATE TABLE `image` (
`Id` int(11) NOT NULL auto_increment,
`Image` blob,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Second,you need a jsp. Below is the HTML block in jsp file:
<form action="TestUploadImageToDB" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="submit">
</form>
Third, you need a servlet to deal with the file upload. Below is the configuration in web.xml and code:
<servlet>
<servlet-name>TestUploadImageToDB</servlet-name>
<servlet-class>com.TestUploadImageToDB</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestUploadImageToDB</servlet-name>
<url-pattern>/TestUploadImageToDB</url-pattern>
</servlet-mapping>
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();
}
}
}
}