本文将阐述怎么使用commons-fileupload将图片上传至mysql数据库,并利用java servlet将其在浏览器中显示
出来。
前提条件:
正确安装了mysql,tomcat,并下载了commons-fileupload-1.0.jar。
1,前台页面
---test_upload.htm---
上传测试
2,上传的后台处理页面
---upload.jsp---
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="java.io.*" %>
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*"%>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="com.cf.model.DbManipulate" %>
<%
DiskFileUpload upload=new DiskFileUpload();
upload.setSizeThreshold(4096);
upload.setRepositoryPath("d:/java/");
upload.setSizeMax(10000000);
List fileItems = upload.parseRequest(request);
Iterator i = fileItems.iterator();
String name = ((FileItem)i.next()).getString();
FileItem fi = (FileItem)i.next();
String fileName = fi.getName();
//System.out.println(fileName);
fileName = fileName.replace(':','_');
fileName = fileName.replace('\\','_');
//System.out.println(fileName);
//File savedFile = new File("d:/java/upload/",fileName);
//fi.write(savedFile);
InputStream fis=fi.getInputStream();
DbManipulate dm=new DbManipulate();
Long long_size=new Long(fi.getSize());
int size=long_size.intValue();
PreparedStatement ps=dm.DbUpdate("insert into photo(image,description) values(?,?)");
ps.setBinaryStream(1,fis,size);
ps.setString(2,fileName);
ps.executeUpdate();
String sql="select id from photo order by id desc limit 1";
PreparedStatement ps2=dm.DbQuery(sql);
ResultSet rs=ps2.executeQuery();
int index=0;
if(rs.next())
{
index=rs.getInt(1);
}
//ps.close();
//fis.chose();
%>
<%=name%>
go on