Jsp页面实现文件上传下载

Jsp页面实现文件上传下载

导包
jsp上传下载需要两个包
在这里插入图片描述

po层

Up.java

public class Up {
	private int id;
	private String yn;
	private String pn;
	public int getId() {
		return id;
	}
	
	public Up(int id, String yn, String pn) {
		this.id = id;
		this.yn = yn;
		this.pn = pn;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getYn() {
		return yn;
	}
	public void setYn(String yn) {
		this.yn = yn;
	}
	public String getPn() {
		return pn;
	}
	public void setPn(String pn) {
		this.pn = pn;
	}
}

dao层

UpDao.java

public interface UpDao {
	public void add(Up up);
	public List<Up> list();
}

c3p0 连接关闭数据库方法

public abstract class BaseDao {
	public ResultSet rs = null;
	public PreparedStatement pstm = null;
	public Connection conn = null;
	
	public Connection getConn() {
		try {
			DataSource ds = new ComboPooledDataSource ();
			conn = ds.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}
	
	public void close() {
		try {
			if(rs != null) {
				rs.close();
				rs = null;
			}
			if(pstm != null) {
				pstm.close();
				pstm = null;
			}
			if(conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

}

UpDaoImpl.java

public class UpDaoImpl extends BaseDao implements UpDao{
	/**
	*添加
	*/
	@Override
	public void add(Up up) {
		// TODO Auto-generated method stub
		try {
			String sql="insert into up(id,yn,pn) values(seq_gz_id.nextval,?,?)";
			conn = getConn();
			pstm = conn.prepareStatement(sql);
			pstm.setString(1, up.getYn());
			pstm.setString(2,up.getPn());
			pstm.execute();
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			close();
		}
	}
	/**
	*查找
	*/
	@Override
	public List<Up> list() {
		// TODO Auto-generated method stub
		List<Up>  list = new ArrayList<Up>();
		try {
			String sql = "select id,yn,pn from up";
			conn= getConn();
			pstm = conn.prepareStatement(sql);
			rs = pstm.executeQuery();
			while(rs.next()) {
				Up up = new Up(rs.getInt("id"), rs.getString("yn"),rs.getString("pn"));
				list.add(up);
			}
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return list;
	}

}

service层

UpService.java

public interface UpService {
	public void add(Up up);
	public List<Up> list();
}

UpServiceImpl.java

public class UpServiceImpl implements UpService{
	private UpDao upDao = new UpDaoImpl();
	
	@Override
	public void add(Up up) {
		// TODO Auto-generated method stub
		upDao.add(up);
	}

	@Override
	public List<Up> list() {
		// TODO Auto-generated method stub
		return upDao.list();
	}
}

jsp

对于文件上传表单处理其中method必须为post,也要增加类型enctype=“multipart/form-data”。这样就可以把文件中的数据作为流式数据上传。当然无论是什么文件格式,均可以。。。
up.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>上传</title> 
</head>
<body>
		<form action="upload.jsp" method="post" enctype="multipart/form-data">
			<input type="text" name="username"/><br>
			<input type="file" name="upload"/><br>
			<input type="submit" value="上传"/>
		</form>
</body>
</html>

load.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
th {
	width: 200px;
	height: 100px;
	background-color: gray;
}
td, th {
	border: solid 1px gray;
	text-align: center;
}
a {
	margin-left: 10px;
}
</style>
</head>
<body>
	<%
		List<Up> us = (List) session.getAttribute("us");
	%>
	<table>
		<tr>
			<th>id</th>
			<th>用户头像</th>
			<th>文件名称</th>
			<th>下载</th>
		</tr>
		<%
			for (int i = 0; i < us.size(); i++) {
			Up u = us.get(i);
		%>
		<tr style="background-color: skyblue">
			<td><%=u.getId() %></td>
			<td><img  src="../<%=u.getYn()%>"></td>
			<td><%=u.getPn() %></td>
			<td><a href="../<%=u.getYn()%>">下载</a></td>
		</tr>
		<%
			}
		%>
	</table>
</body>
</html>

upload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% 
	//设置上传的目录路径
	String path = request.getRealPath("/")+"temp\\";
	String  tpath = path.substring(path.indexOf("demo"))+"\\";//要上传的目录
	//	获取当前文件和文件名称
	boolean isMultipart = ServletFileUpload.isMultipartContent(request); //验证表单是否包含附件

	//1. 创建 DiskFileItemFactory 用于限制文件大小之类的参数,如果不写的话,那就是默认值了
	DiskFileItemFactory disk = new DiskFileItemFactory();
	disk.setSizeThreshold(1024*1024*5); //设置上传附件大小限制为5M
	ServletFileUpload up = new  ServletFileUpload(disk); //创建一个文件上传的处理器
	List<FileItem> its = up.parseRequest(request);
	Date date = new Date();
	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
	String time = sdf.format(date);
	UpService upService = new UpServiceImpl();
	Up  u = null;
	for(FileItem fileitem : its){
		if(fileitem.isFormField()){ //文字
			if(fileitem.getFieldName().equals("username")){
				String username = fileitem.getString();
				out.print(username);
				System.out.println("表单字段的name:"+fileItem.getFieldName());
                System.out.println("表单字段的value"+fileItem.getString("utf-8"));
			}
		}else{  //处理文件			
			tpath +=time+fileitem.getName();  //相对路径
			path+= time+fileitem.getName(); //绝对路径
			u = new Up(0,tpath,fileitem.getName());
			File file = new File(path);
			fileitem.write(file);
		}
	}
	upService.add(u);
	List<Up> us= upService.list();
	session.setAttribute("us", us);
	response.sendRedirect("load.jsp");
%>
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
文件下载是Web开发中常见的功能,可以通过servlet+jsp实现。下面是一个简单的示例: 1. 文件jsp页面中,使用form表单向servlet提交文件: ```html <form method="post" action="UploadServlet" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="上"> </form> ``` 在servlet中,使用Apache Commons FileUpload来处理文件: ```java protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 检查是否是文件请求 if (!ServletFileUpload.isMultipartContent(request)) { response.getWriter().println("不是文件请求"); return; } // 创建文件工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); // 设置缓冲区大小,超过这个大小的文件将被写入临时文件 factory.setSizeThreshold(1024 * 1024 * 10); // 10MB // 设置临时文件存放目录 File tmpDir = new File("tmp"); if (!tmpDir.exists()) { tmpDir.mkdirs(); } factory.setRepository(tmpDir); // 创建文件处理器 ServletFileUpload upload = new ServletFileUpload(factory); // 设置上文件的大小限制 upload.setFileSizeMax(1024 * 1024 * 100); // 100MB // 解析上文件 try { List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { // 保存上文件 String fileName = item.getName(); String destPath = "upload/" + fileName; File destFile = new File(destPath); item.write(destFile); } } response.getWriter().println("上成功"); } catch (Exception e) { e.printStackTrace(); response.getWriter().println("上失败"); } } ``` 2. 文件下载jsp页面中,使用a标签指向servlet,并将要下载文件名作为参数: ```html <a href="DownloadServlet?fileName=test.txt">下载</a> ``` 在servlet中,读取要下载文件并将文件内容输出到response中: ```java protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String fileName = request.getParameter("fileName"); String filePath = "upload/" + fileName; File file = new File(filePath); if (!file.exists()) { response.getWriter().println("文件不存在"); return; } // 设置响应头,让浏览器下载文件 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); response.setContentType("application/octet-stream"); // 输出文件内容 InputStream in = new FileInputStream(file); OutputStream out = response.getOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } in.close(); out.close(); } ``` 以上就是一个简单的servlet+jsp文件下载实现。当然,这只是一个基础示例,实际应用中还需要考虑更多的情况,比如文件的安全性、文件的命名规则等等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值