文件上传和下载

文件上传和下载

1.文件上传

导包:commons-fileupload .jar commons-io .jar

1.1文件上传表单的三个要素

  1. 表单的提交的方式需要是POST
  2. 表单中需要有<input type=”file”素,需要有name属性和值。
  3. 表单enctype=”multipart/form-data”

1.2文件上传的步骤

  1. 创建磁盘文件项工厂

    DiskFileItemFactory df = new DiskFileItemFactory();

  2. 创建核心文件解析类

    ServletFileUpload sf = new ServletFileUpload(df);

  3. 解析请求

    list list = sf.parseRequest(request);

  4. 遍历集合,判断请求项 for(FileItem f:list)

    1. 若不是普通项 ! f.isFormItem()

      获取文件名, f.getName()

      获取文件内容(输入流)f.getInputStream()

      创建输出流 getServletContext.getRealPath(“存储路径”) ; OutPutStream os = new fileOutPutStream(realPath+”\“+filename);

      IO流写入文件

    2. 普通项

      获取参数名 f.getFileName()

      获取内容 f.getString();//可传入编码格式解决中文乱码问题

1.3 文件上传的Servlet

//1.创建磁盘文件项工厂DiskFileItemFactory

//创建一个核心的解析类ServletFileUpload

//利用核心类解析Request,解析后会得到多个部分,返回一个list集合 parseRequest

//遍历list集合,得到代表每个部分的文件项的对象.根据文件项判断是否为文件上传项

isFormItem()

文件上传的API

1.4 DiskFileItemFactory:磁盘文件项工厂

sizeThreshold 设置文件上传的缓冲区大小,默认10kb

Repository 临时文件存放路径

1.5 ServletFileUpload:核心解析类

FileItemFactory

isMutipartContent:判断恩仇type属性是否为multipart/form-data

parseRequest:解析request对象,返回一个list集合(每个部分的文件对象)

setFileSizeMax:设置单个文件的大小

setSizeMax:设置上传文件的总大小

setHeaderEncoding :设置中文文件名乱码的问题

setProgressListener:设置监听文件上传的进度

1.6 FileItem

isFormField:是否为普通项

getFieldName:获得普通项名字

getString:获得普通项内容

getName获得文件上传项名称

getInputStream:获得上传项内容

1.7 getSize获得上传文件大小

getContentType:获得上传文件格式

delete删除临时文件

//相同文件名文件上传解决办法

UUID.randomUUID().toString().relplace(“-“,””)+fliename.substring(filename.lastIndexOf(“.”));

//同一文件夹文件过多解决

文件上传代码

downloadServlet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.itheima.utils.UUIDUtils;

/**
* 上传Servlet
*/
public class uploadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
// request.setCharacterEncoding("UTF-8");
// 1.创建磁盘文件项工厂
DiskFileItemFactory fileitemfactory = new DiskFileItemFactory();
// 设置文件缓冲区大小
fileitemfactory.setSizeThreshold(1024 * 1024 * 3);
// 设置临时文件路径
String path = getServletContext().getRealPath("/temp");
fileitemfactory.setRepository(new File(path));
// 2.创建核心解析类
ServletFileUpload si = new ServletFileUpload(fileitemfactory);
// 解决中文文件名乱码问题
si.setHeaderEncoding("UTF-8");
// 3.解析请求
List<FileItem> parseRequest = si.parseRequest(request);
// 4. 判断文件上传项
for (FileItem fileItem : parseRequest) {
if (fileItem.isFormField()) {
// 基础项
String name = f.getFieldName();
// String content = f.getString();
// 解决获取普通项内容乱码的问题
String content = f.getString("UTF-8");
System.out.println(name + "---" + content);
} else {
// 文件上传项
// 获取文件名
String filename = fileItem.getName();
// 解决文件名重复的问题,UUID
filename = UUIDUtils.getUUID(filename);
// 处理ie浏览器文件名带路径的问题
if (filename.lastIndexOf("\\") != -1) {
filename = filename.substring(filename
.lastIndexOf("\\") + 1);
}
// 获取文件内容
InputStream is = fileItem.getInputStream();
// 获取上传路径
String realPath = getServletContext().getRealPath(
"/upload");
// 创建输出流
String path2 = UUIDUtils.getPath(filename);
String path3 = realPath + path2;
File file = new File(path3);
if (!file.exists()) {
file.mkdirs();
}
OutputStream os = new FileOutputStream(path3 + "\\"
+ filename);
// 上传
int len;
byte[] b = new byte[1024];
while ((len = is.read(b)) != -1) {
os.write(b, 0, len);
}
// 关闭流
is.close();
os.close();
// 删除临时文件
fileItem.delete();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}

upload.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<%@ 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>Insert title here</title>
<script type="text/javascript">
function add() {
document.getElementById("div1").innerHTML += "<div><input type='file' name='updowm'><input type='button' value='删除' onclick='del(this)'></div>";
}
function del(who) {
who.parentNode.parentNode.removeChild(who.parentNode);
}
</script>
</head>
<body>
<h1>上传页面</h1>
<form action="${pageContext.request.contextPath }/uploadServlet"
method="post" enctype="multipart/form-data">
<input type="button" value="添加" onclick="add()"><input
type="submit" value="上传"><br>
<div id="div1"></div>
</form>
</body>
</html>

2.文件下载

2.1 文件下载流程

  1. 获取数据

    String filename = request.getParameter(“filename”);

  2. 设置两个头和一个输入流

    1. 设置两个头

      设置Content-Type

      response.setContentType(“getServletContext().getMimeType(filename)”);

      设置Content-Disposition

      response.setHeader(“Content-Disposition”,”attachment;filename=”+filename)

    2. 设置输入流

      String path=getServletContext().getRealPath(“/download”);

      InputStream is = new FileInputStream(path+”/“+filename);

  3. 获取输出流

    ​ OutPutStream os = response.getOutputStream();

2.2文件下载代码

downloadServlet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.itheima.utils.DownloadEncodingUtils;

/**
* 文件下载Servlet
*/
public class downloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 获取数据
String filename = request.getParameter("filename");
// 解决文件名中文乱码问题
filename = new String(filename.getBytes("ISO-8859-1"), "UTF-8");
// 设置两个头,一个流
// 设置ContentType
response.setContentType(getServletContext().getMimeType(filename));
// 设置输入流
String realPath = getServletContext().getRealPath("/download");
InputStream is = new FileInputStream(realPath + "/" + filename);
System.out.println(filename);
// 解决不同浏览器文件名中文显示问题
String agent = request.getHeader("User-Agent");
if (agent.contains("Firefox")) {
// 火狐浏览器
filename = DownloadEncodingUtils.base64EncodeFileName(filename);
} else {
filename = URLEncoder.encode(filename, "UTF-8");
filename = filename.replace("+", " ");
}
// 设置Content-Disposition
System.out.println(filename);
response.setHeader("Content-Disposition", "attachment;filename="
+ filename);
// 获取输出流
ServletOutputStream os = response.getOutputStream();
int len = 0;
byte[] b = new byte[1024];
while ((len = is.read(b)) != -1) {
os.write(b, 0, len);
}
is.close();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

download.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<%@ 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>Insert title here</title>
</head>
<body>
<h1>文件下载</h1>
<a href="${pageContext.request.contextPath }/download/psb.jpg">psb.jpg</a>
<h3>手动下载</h3>
<a
href="${pageContext.request.contextPath }/downloadServlet?filename=psb.jpg">psb.jpg</a>
<br>
<a
href="${pageContext.request.contextPath }/downloadServlet?filename=中文.jpg">中文.jpg</a>
</body>
</html>

2.3 文件列表下载

multiDownloadServlet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.itheima.utils.DownloadEncodingUtils;

/**
* Servlet implementation class multidownloadServlet
*/
public class multidownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String path = request.getParameter("path");
path = new String(path.getBytes("ISO-8859-1"), "UTF-8");
File file = new File(path);
String filename = file.getName();
// 设置两个头,一个流
response.setContentType(getServletContext().getMimeType(filename));
InputStream is = new FileInputStream(file);
// 处理中文名
String agent = request.getHeader("User-Agent");
if (agent.contains("Firefox")) {
filename = DownloadEncodingUtils.base64EncodeFileName(filename);
} else {
filename = URLEncoder.encode(filename, "UTF-8");
filename = filename.replace("+", " ");
}
response.setHeader("Content-Disposition", "attach;filename=" + filename);
ServletOutputStream os = response.getOutputStream();
int len = 0;
byte[] b = new byte[1024];
while ((len = is.read(b)) != -1) {
os.write(b, 0, len);
}
//关闭流
is.close();
os.close();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

multiDownload.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<%@page import="java.io.File"%>
<%@page import="java.util.*"%>
<%@page import="java.util.LinkedList"%>
<%@ 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>Insert title here</title>
</head>
<body>
<h1>多文件下载</h1>
<%
//创建队列
Queue<File> queue = new LinkedList<File>();
//创建根节点
File root = new File(
"F:\\java基础增强\\javaweb_day19(文件上传和下载)\\资料\\下载资料列表");
//根节点入队
queue.offer(root);
while (!queue.isEmpty()) {
//出队
File file = queue.poll();
//获取出队元素的所有子元素
File[] files = file.listFiles();
//遍历子元素
for (File f : files) {
if (f.isFile()) {
//为标准文件,则输出
%>
<h3>
<a
href="${pageContext.request.contextPath }/multidownloadServlet?path=<%=f.getCanonicalPath()%>"><%=f.getName()%></a>
</h3>
<%
} else {
//不是标准文件,则入队
queue.offer(f);
}
}
}
%>
</body>
</html>

日历对象 Calendar

1
Calendar cal = Calendar.getInstance();