1、编写upload.jsp,文件上传表单
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传文件</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
//点击新增文件按钮,添加一个上传文件的按钮
function addFile(){
//var $file = $(".files:first").clone();
var str = '<div class="files"><input type="file" name="mf"><a href="javascript:;" onclick="delFile(this)">删除</a></div>';
$(":submit").before(str);
};
//删除
function delFile(obj){
$(obj).parent().remove();
};
</script>
</head>
<body>
<form action="upload.do" method="post" enctype="multipart/form-data">
请选择上传图片:<a href="javascript:addFile();">新增文件</a><br/>
<div class="files"><input type="file" name="mf"></div>
<input type="submit" value="上传">
</form>
</body>
</html>
2、编写文件上传的Servlet,导入jar包
/** 文件上传 */
public class UploadServlet extends HttpServlet{
public void service(HttpServletRequest request,HttpServletResponse response) throws IOException{
// 获取请求提交过来的文件信息
/** 获取请求提交的文件信息,使用(commons-fileupload.jar)
* commons-fileupload.jar是Apache旗下的工具包(是一款上传文件的解析器),我们使用它解析request的信息
* 它可以将字节从request里面提取出来,并且封装成对象
*/
// 构建一个imageDao
ImageDao imageDao = new JdbcImageDao();
//参数设置
DiskFileItemFactory factory = new DiskFileItemFactory();
// 利用factory设置临时文件保存目录,上传大小控制
ServletFileUpload fileUpload = new ServletFileUpload(factory);
try {
//解析request里的文件信息,返回一个List集合
List<FileItem> list = fileUpload.parseRequest(request);
for(FileItem item : list){
System.out.println("文件名称:"+item.getName());
System.out.println("文件大小"+item.getSize());
System.out.println("文件类型"+item.getContentType());
System.out.println("上传的元素名"+item.getFieldName());
// 将文件保存到目标位置 F盘下
// 使用UUID生成唯一性存储型图片名,防止图片之间相互覆盖
UUID uuid = UUID.randomUUID();
String destName = uuid.toString().replaceAll("-", "");
//获取图片的扩展名
int index = item.getName().lastIndexOf(".");
String type = item.getName().substring(index);
//将图片上传到tomcat/webapps/项目的images目录
//获取物理路径
String realPath = request.getServletContext().getRealPath("images");
File pathFile = new File(realPath);
if(!pathFile.exists()){
pathFile.mkdirs(); //目录不存在,则创建目录
}
File destFile = new File(realPath+"\\"+destName+type);
System.out.println(destFile.getPath());
item.write(destFile);
//将文件信息写入数据库
Image image = new Image();
image.setName(item.getName());
image.setSize(item.getSize());
image.setPic(destName+type); //存储的文件名
// 获取当前上传时间
image.setTime(new Timestamp(System.currentTimeMillis()));
//插入数据库
imageDao.save(image);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
编写Web.xml的配置文件
<!-- 文件上传 -->
<servlet>
<servlet-name>uploadServlet</servlet-name>
<servlet-class>
com.up.servlet.UploadServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>uploadServlet</servlet-name>
<url-pattern>/upload.do</url-pattern>
</servlet-mapping>
建表存入图片数据
create table t_image(
p_id number primary key,
p_name varchar2(100), /* 图片原名称 */
p_size number, /* 图片大小 */
p_pic varchar2(100), /* 图片存储名称 */
p_time timestamp(6) /* 上传时间 */
);
drop sequence image_seq;
create sequence image_seq;
创建图片信息的实体类
public class Image implements Serializable{
private Integer id;
private String name;
private Long size;
private String pic;
private Timestamp time;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getSize() {
return size;
}
public void setSize(Long size) {
this.size = size;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
}
编写图片上传和查看的DAO接口
public interface ImageDao {
public void save(Image image);
public List<Image> findAll();
}
编写DAO接口的实现类
public class JdbcImageDao implements ImageDao{
//图片上传
@Override
public void save(Image image) {
String sql = "insert into t_image "
+ "(p_id,p_name,p_size,p_pic,p_time)"
+ " values (image_seq.nextval,?,?,?,?)";
try {
Connection conn = DbUtil.openConnection();
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, image.getName());
pst.setLong(2, image.getSize());
pst.setString(3, image.getPic());
pst.setTimestamp(4, image.getTime());
pst.executeUpdate();//执行
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("数据库访问异常",e);
}finally{
DbUtil.closeConnection();
}
}
//查看图片
@Override
public List<Image> findAll() {
String sql = "select * from t_image order by p_time desc";
try {
Connection conn = DbUtil.openConnection();
PreparedStatement pst = conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
List<Image> list = new ArrayList<Image>();
while(rs.next()){
Image image = new Image();
image.setId(rs.getInt("p_id"));
image.setName(rs.getString("p_name"));
image.setSize(rs.getLong("p_size"));
image.setPic(rs.getString("p_pic"));
image.setTime(rs.getTimestamp("p_time"));
list.add(image);
}
return list;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException("数据库访问异常",e);
}finally{
DbUtil.closeConnection();
}
}
}
编写JdbcUtil工具类
public final class DbUtil {
private static ThreadLocal<Connection> threadLocal
= new ThreadLocal<Connection>();
static{
try {
Class.forName("oracle.jdbc.OracleDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection openConnection() throws SQLException{
//先从threadLocal尝试获取Connection
Connection conn = threadLocal.get();//利用线程ID
//如果存在就直接返回,不存在就新建connection并放入threadLocal
if(conn == null){
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:XE",
"system", "123456");
threadLocal.set(conn);//线程ID conn对象
}
return conn;
}
public static void closeConnection(){
Connection conn = threadLocal.get();//利用线程ID
if(conn != null){
threadLocal.set(null);
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws SQLException{
Connection conn = DbUtil.openConnection();
System.out.println(conn);
DbUtil.closeConnection();
}
}
注意:不要忘了修改JdbcUtil的配置信息,主机地址,账户,密码等
conn = DriverManager.getConnection(
“jdbc:oracle:thin:@localhost:1521:XE”,
“system”, “123456”);
编写查看图片的 view.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传文件</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<table>
<c:forEach items="${images}" var="image">
<tr>
<td>${image.id}</td>
<td>${image.name}</td>
<td>${image.size}</td>
<td><img width="30px" height="30px" src="images/${image.pic}" /></td>
<td>${image.time}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
编写查看图片的Servlet
public class ViewServlet extends HttpServlet{
@Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//调用ImageDao查询
ImageDao imageDao = new JdbcImageDao();
List<Image> list = imageDao.findAll();
//将集合放入request
request.setAttribute("images",list);
// 跳转到view.jsp
request.getRequestDispatcher("view.jsp").forward(request, response);
}
}
编写查看图片的Web.xml
<!-- 文件查看 -->
<servlet>
<servlet-name>viewServlet</servlet-name>
<servlet-class>
com.up.servlet.ViewServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>viewServlet</servlet-name>
<url-pattern>/view.do</url-pattern>
</servlet-mapping>