专门用于实现文件上传下载的免费组件
特点
缺点
1、将commons-fileupload
组件导入工程
<!-- upload file -->
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
2、提交文件的表单需要为
<form enctype="multipart/form-data" method="post">
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//判断请求消息内容是否为:multipart/form-data多段类型
if (ServletFileUpload.isMultipartContent(req)){
//获取ServletFileUpload对象
ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
try {
//利用ServletFileUpload对象的parseRequest()获取一个存放表单信息FileItem对象的集合
List<FileItem> list = servletFileUpload.parseRequest(req);
//遍历集合
for (FileItem fileItem : list){
//判断该对象是否为普通表单字段
if (fileItem.isFormField()){
//获取该字段的name属性值
String name = fileItem.getFieldName();
//获取该字段的value,并转码为utf-8
String value = fileItem.getString("utf-8");
System.out.println(name + ":" + value);
//否则,为文件类型
}else {
String name = fileItem.getFieldName();
//获取上传字段的文件名
String fileName = fileItem.getName();
System.out.println(fileName);
//如果名字是空字符串,就证明没有上传
if (fileName.isEmpty()){
System.out.println(name + "没有上传文件");
}else {
//存放在项目中的位置,如果没有,就创建
String path = "test/";
File file = new File(req.getServletContext().getRealPath("/") + path);
file.mkdirs();
//存放文件
fileItem.write(new File(req.getServletContext().getRealPath("/") + path + fileName));
System.out.println("文件上传完毕");
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获得文件路径
String filePath = req.getParameter("filePath");
//将需要下载的文件写入输入流
FileInputStream fileInputStream = new FileInputStream(req.getServletContext().getRealPath("/") + filePath);
//对文件路径字符串进行分割,获得文件名
String fileName = filePath.split("/")[1];
//中文名字需要编码后传输
String fileName = URLEncoder.encode("测试文件.doc", "UTF-8");
//设置响应头,告诉浏览器该文件应该下载,并设置文件名
resp.setHeader("Content-Disposition","attachment;filename=" + fileName);
//前后端分离需要主动暴露响应头给前端
resp.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
//告知浏览器这是一个字节流,浏览器处理字节流的默认方式就是下载
resp.setHeader("Content-Type","multipart/form-data");
//设置字符集编码
resp.setCharacterEncoding("utf-8");
//获得输出流
ServletOutputStream outputStream = resp.getOutputStream();
//调用方法,进行下载
IOUtils.copy(fileInputStream,outputStream);
//关闭资源
outputStream.flush();
outputStream.close();
fileInputStream.close();
}