文件上传
1.upload.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
侠侣称谓:<input type="text" name="cpname" placeholder="阁下名讳是?"><br>
侠士:<input type="file" name="male"><br>
巾帼:<input type="file" name="female"><br>
<input type="submit">
</form>
</body>
</html>
1.2 将表单中的input分装到一个类中,UploadInfo类,方便在后续操作表单中通过input上传的数据、文件
package com.qfedu.pojo;
public class UploadInfo {
private String idcard;
private String zheng;
private String fan;
public String getIdcard() {
return idcard;
}
public void setIdcard(String idcard) {
this.idcard = idcard;
}
public String getZheng() {
return zheng;
}
public void setZheng(String zheng) {
this.zheng = zheng;
}
public String getFan() {
return fan;
}
public void setFan(String fan) {
this.fan = fan;
}
}
客户端发起上传请求到达UploadServlet,处理文件
2.UploadServlet.java
@WebServlet("/upload")
public class UploadServlet extends HttpServlet{
//创建一个将前端上传的数据作为变量的对象,可以用通过该对象的set、get方法修改和获取上传的数据
private UploadInfo uploadInfo = new UploadInfo();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*
1获取表单中的文件对象
2把文件保存在服务器的文件夹中
*/
// DiskFileItemFactory用来设置临时存储目录和缓冲区大小
DiskFileItemFactory dfif = new DiskFileItemFactory();
//以字节为单位设置内存缓冲大小
dfif.setSizeThreshold(1024*1024*5);
//设置临时存储目录,允许和最终文件保存在同一目录
File temp = new File("D:/PPT/upload");
//指定文件保存目录时,先判断该目录是否存在,不存在时需创建该目录
if (temp.exists()) {
temp.mkdir();
}
//设置临时保存目录
dfif.setRepository(temp);
// ServletFileUpload提供了对请求的解析,和请求大小限制的相关功能
ServletFileUpload sf = new ServletFileUpload(dfif);
//设置上传的一个文件的大小限制
sf.setFileSizeMax(1024*1024*5);
//设置表单中所有input加起来的上传大小
sf.setSizeMax(1024*1024*10);
try {
//解析请求,返回的是form表单中所有带有name属性的input的数据的封装对象List集合
List<FileItem> list = sf.parseRequest(req);
//遍历list,获取到上传的数据
for (FileItem fileItem : list) {
//判断上传的是否是普通文本表单
if(fileItem.isFormField()) {
//是普通文本表单,则将其上传编码格式设为utf-8,解决中文乱码问题
//现在获取到的是字节,所以获取表单内容不使用getParaMeter
String value = fileItem.getString("utf-8");
System.out.println(value);
//将获取到的文件名通过set方法设置给当前文件
if ("cpname".equals(fileItem.getFieldName())) {
uploadInfo.setCpname(value);
}
} else {
//获取到包括后缀的文件名
String filename = fileItem.getName();
//获取到后缀名在完整文件名中的位置
int lastIndex = filename.lastIndexOf(".");
//获取到 “.后缀名”
String sufName = filename.substring(lastIndex);
//随机生成一个不重复的文件名
String finalName = UUID.randomUUID().toString().replace("-", "") + sufName;
//不是普通文本而是一个文件 ,这时可以执行上传,但需要判断用户是否已经选择文件
//选择文件了,将文件写入到指定文件夹中
if (filename != null && filename.length() > 0) {
//write用于把文件写入到服务器指定的文件中
fileItem.write(new File("D:/PPT/upload/" + finalName));
//获得fileItem对应的表单的name属性的值
String filedName = fileItem.getFieldName();
//将获取到的文件名通过set方法设置给当前文件
if ("male".equals(filedName)) {
uploadInfo.setMale(finalName);
}
//将获取到的文件名通过set方法设置给当前文件
if ("female".equals(filedName)) {
uploadInfo.setFemale(finalName);
}
} else {
//未选择文件,返回选择文件界面重新选择文件
resp.sendRedirect("/FirstUpload/upload.html");
return;
}
}
}
String sql = "insert into couple values(null,?,?,?)";
ArrayList<Object> datas = new ArrayList<Object>();
datas.add(uploadInfo.getCpname());
datas.add(uploadInfo.getMale());
datas.add(uploadInfo.getFemale());
//将文件名传输到数据库 之后在展示界面通过通过 URL?文件名 方式下载文件
DdUtils.update(sql, datas);
//重定向到ListServlet
resp.sendRedirect("/FirstUpload/list");
} catch (Exception e) {
e.printStackTrace();
resp.sendRedirect("/FirstUpload/error.html");
}
}
}
在UploadServlet中将从前端获取到的数据文件存放到数据库中,然后重定向到ListServlet中,从数据库获取到文件并渲染到list.jsp前端进行展示
3.ListServlet.java
@WebServlet("/list")
public class ListServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//从数据库中获取文件信息
String sql = "select * from upload";
try {
List<HashMap<String, Object>> datas = DdUtils.query(sql, null);
req.setAttribute("datas", datas);
//转发到WEB-INF/list.jsp
req.getRequestDispatcher("WEB-INF/list.jsp").forward(req, resp);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}}
从ListServlet中渲染数据到list.jsp进行展示
4.list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>Insert title here</title>
</head>
<body>
<ul>
//${datas} 获取到的datas数据集合 uploadinfo为当前对象
<c:forEach items="${datas}" var="uploadinfo">
//<a href="download?name=${uploadinfo.zheng}"> 发送请求到DownloadServlet,获取对应文件
<li>${uploadinfo.idcard}|<a href="download?name=${uploadinfo.zheng}">${uploadinfo.zheng }</a>|
<a href="download?name=${uploadinfo.fan}">${uploadinfo.fan }</a></li>
</c:forEach>
</ul>
</body>
</html>
文件下载
5.DownloadServlet.java
@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取前端传入的需要下载的文件名字
String name = req.getParameter("name");
File file = new File("Z:/windos/files/" + name);
resp.setContentType("application/octet-stream");
// 设置文件名字,我们只需要修改filename=后面的文件名,其他是固定的字符串
// 文件下载的时候如果文件的名字是中文,会出现乱码
resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
// 把文件转成字节输出
resp.getOutputStream().write(FileUtils.readFileToByteArray(file));
}