第一步,导包:commons-fileupload-1.2.1.jar,commons-io-1.4.jar
一、文件上传
主要是使用到两个接口:
DiskFileItemFactory,ServletFileUpload
public class UploadServlet extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
try{
// 创建文件上传工程
FileItemFactory fac = new DiskFileItemFactory();
// 创建文件上传核心类
ServletFileUpload upload = new ServletFileUpload(fac);
// 设置单个文件大小
upload.setFileSizeMax(10 * 1024 * 1024);//10M
// 设置所有文件大小
upload.setSizeMax(100 * 1024 * 1024);//100M
// 设置上传表单文件名编码
upload.setHeaderEncoding("UTF-8");
// 如果表单是文件上传表单
if(upload.isMultipartContent(request)){
// 把请求数据转换为FileItem对象集合
List<FileItem> list = upload.parseRequest(request);
for(FileItem item : list){
//如果是普通文本内容
if(item.isFormField){
String fieldName = item.getFieldName();// 表单元素名称
String content = item.getString();//可以传入参数“UTF-8”处理中文
}else{
// 如果是上传文件
// 表单元素名称
String fieldName = item.getFieldName();
// 文件名
String name = item.getName();
String content = item.getString();
String type = item.getContentType;//文件类型
InputStream in = item.getInputStream();//上传文件流
// 处理文件重名问题
String preName = UUID.randomUUID().toString();
name = preName + "*" + name;
// 获取上传路径(WebRoot路径下创建一个upload文件夹)
String path = getServletContext().getRealPath("/upload");
// 创建文件
File file = new File(path,name);
// 上传文件
item.write(file);
// 删除临时文件
item.delete();
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
this.doGet(request, response);
}
}
设置表单为文件上传表单
<!-- 通过enctype属性设置文件上传表单 -->
<form id="formId" action="${pageContext.request.contextPath}/upload/uploadServlet" method="post" enctype="multipart/form-data"></form>
二、文件下载
// 跳转文件下载页面
public void down(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
// 创建map集合,保存唯一文件名(key),文件简单名(value)
Map<String,String> map = new HashMap<String,String>();
// 获取上传目录
String path = getServletContext().getRealPath("/upload");
File file = new File(path);
// 所有文件文件名
String[] list = file.list();
if(list != null && list.length > 0){
for(int i=0;i<list.length;i++){
String fileName = list[i];
String shortName = fileName.substring(fileName.lastIndexOf("*")+1);
map.put(fileName,shortName);
}
request.setAttribute("fileName",map);
request.getRequestDicpatcher("/down.jsp").forward(request,response);
}
}
// 文件下载方法
public void downFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
// 获取文件名
String fileName = request.getParameter("fileName");
fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");
// 文件上传路径
String path = getServletContext.getRealPath("/upload");
// 获取文件流
InputStream in = new FileInputStream(new File(path,fileName));
// 对中文文件名进行编码
fileName = URLEncoder.encode(fileName,"UTF-8");
// 设置下载的响应头
response.setHeader("content-disposition","attachment;fileName=" + fileName);
// 获取response字节流
OutputStream out = response.getOutputStream();
byte[] b = new byte[1024];
int len = -1;
if((len = in.read(b)) != -1){
out.write(b, 0, len);
}
out.close();
in.close();
}
jsp页面:
<body>
<table border="1" align="center">
<tr>
<td>序号</td>
<td>文件名</td>
<td>操作</td>
</tr>
<c:forEach var="file" value="${requestScope.fileName}" varStatus="vs">
<tr>
<td>${vs.count}</td>
<td>${file.value}</td>
<td>
<a href="${pageContext.request.contextPath}/fileServlet?fileName="+${file.key}>下载</a>
</td>
</tr>
</c:forEach>
</body>