目录结构
文件的上传
一,准备工作
1.导入依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
2.前端页面核心代码
请求页面
<%--
enctype:编码类型,multipart/form-data是指表单数据有多个部分组成,既有文件又有二进制数据组成。
GET:对上传文件大小有限制。
POST:对上传文件大小没有限制。
--%>
<form action="upload" method="post" enctype="multipart/form-data">
上传用户:<input type="text" name="username"> <br>
<p><input type="file" name="file1"></p>
<p><input type="file" name="file2"></p>
<p><input type="submit">|<input type="reset"></p>
</form>
响应页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<p>${requestScope.msg}</p>
</body>
</html>
3.web.xml配置映射Servlet
<servlet>
<servlet-name>uploadServlet</servlet-name>
<servlet-class>com.kuang.cotroller.UpLoadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>uploadServlet</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
二,后端代码实现
public class UpLoadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 上传文件保存路径
String uploadDir = null;
// 上传文件临时保存路径
String tmpDir = null;
// 上传文件的文件名
String fileUploadName = null;
/*
* 创建上传文件的保存路径和临时路径,建议在WEB-INF路径下,安全,用户无法直接访问上传的文件
* */
uploadDir = this.getServletContext().getRealPath("/WEB-INF/upload");
tmpDir = this.getServletContext().getRealPath("/WEB-INF/tmp");
File uploadFile = new File(uploadDir);
if(!uploadFile.exists()){
uploadFile.mkdir();
}
File tmpFile = new File(tmpDir);
if(!tmpFile.exists()){
tmpFile.mkdir();
}
/*
* 判断表单是否为POST方式提交,是否还有enctype="multipart/form-data"属性
* */
if(!ServletFileUpload.isMultipartContent(req)){
// 普通表单,返回错误消息
req.setAttribute("msg","文件上传失败");
resp.setContentType("text/html;charset=utf-8");
req.getRequestDispatcher("/result.jsp").forward(req,resp);
return;
}
/*
* 创建DiskFileItemFactory对象,处理文件路径或者大小限制
* 通过这个工厂设置一个缓冲区,当上传文件大于这个缓冲区(内存)的时候,将他放到临时文件夹中
*
* 当上传文件小于1mb时,默认将该文件加载到内存中。
* 当上传文件大于1mb时,默认将该文件存储到临时文件夹中。
* */
DiskFileItemFactory factory = new DiskFileItemFactory(1024*1024,tmpFile);
/*
* 创建ServletFileUpload
* */
ServletFileUpload upload = new ServletFileUpload(factory);
// 监听长传进度
upload.setProgressListener(new ProgressListener() {
// pBYtesRead:已读取到的文件大小
// pContextLength:文件大小
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("总大小:" + pContentLength + "已上传:" + pBytesRead);
}
});
// 处理乱码问题
upload.setHeaderEncoding("UTF-8");
// 设置单个文件的最大值 10MB
upload.setFileSizeMax(1024 * 1024 * 10);
try {
List<FileItem> fileItems = upload.parseRequest(req);
for (FileItem fileItem : fileItems) {
if(fileItem.isFormField()){
// 普通表单数据
System.out.println(fileItem.getFieldName()+"==="+fileItem.getString("UTF-8"));
continue;
}
// 文件表单数据数据
fileUploadName = fileItem.getName();
if(fileUploadName.trim().equals("") || fileUploadName == null){
continue;
}
System.out.println("上传文件名:"+fileUploadName);
// 当前文件真实存储路径
String realPath = uploadDir + "/" + UUID.randomUUID();
File realPathFile = new File(realPath);
if(!realPathFile.exists()){
realPathFile.mkdir();
}
// 文件存储
InputStream input = fileItem.getInputStream();
FileOutputStream output = new FileOutputStream(realPath + "/" + fileUploadName);
int len = 0;
byte[] buffer = new byte[1024];
while((len = input.read(buffer)) != -1){
output.write(buffer,0,len);
}
output.close();
input.close();
// 清除临时文件
fileItem.delete();
}
} catch (FileUploadException e) {
// 文件超出规定大小
e.printStackTrace();
return;
}
req.setAttribute("msg","文件上传成功");
resp.setContentType("text/html;charset=utf-8");
// 必须使用请求转发的方式显示该页面,不然请求作用域对象的数据全部丢失,无法显示提示信息
req.getRequestDispatcher("/result.jsp").forward(req,resp);
}
}
文件的下载
一,准备工作
1.前端页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<a href="<%=request.getContextPath()%>/downLoad">下载文件</a>
</body>
</html>
2.web.xml配置映射Servlet
<servlet>
<servlet-name>downLoadServlet</servlet-name>
<servlet-class>com.kuang.controller.DownLoadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>downLoadServlet</servlet-name>
<url-pattern>/downLoad</url-pattern>
</servlet-mapping>
二,后端代码实现
public class DownLoadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String realPath = request.getServletContext().getRealPath("/static/readme.txt");
String fileName = realPath.substring(realPath.lastIndexOf('/')+1);
// 设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西
response.setHeader("Content-Disposition","attachment;filename"+fileName);
InputStream input = new BufferedInputStream(new FileInputStream(realPath));
ServletOutputStream output = response.getOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = input.read(buffer)) != -1){
output.write(buffer,0,len);
}
output.flush();
output.close();
input.close();
}
}
B站地址:https://space.bilibili.com/95256449