文件上传的准备
1:准备表单
请求方式:post
enctype设置为:multipart/form-data
将enctype设置为multipart/form-data之后就不能在使用req.getParameter()
2:导入jar包
commons-fileupload-1.2.2.jar
commons-io-1.4.jar
* 创建表单
<%@ page language="java" contentType="text/html; charset=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>
<span style="color: red">${errorMsg}</span>
<form action="/upload" method="post" enctype="multipart/form-data">
姓名:<input name="name" /><br/>
年龄:<input name="age" /><br/>
头像:<input type="file" name="headImg" /><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
FileUploadServlet
public class FileUploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { if (!ServletFileUpload.isMultipartContent(req)) { return; //判断提交的表单是否合法 } ServletFileUpload upload = new ServletFileUpload( new DiskFileItemFactory()); //创建文件解析器包含改工厂类对象 List<FileItem> list = upload.parseRequest(req);//解析请求 for (FileItem item : list) { //迭代控件集合 if (!item.isFormField()) { //不是普通控件时 UUID uuid = UUID.randomUUID(); //获取文件名 //获取文件夹的绝对路径 String path = req.getServletContext().getRealPath("upload"); String extension = FilenameUtils.getExtension(item .getName()); //获取文件的后缀名 item.write(new File(path + "\\" + uuid + "." + extension)); } //调用write方法上传文件 } } catch (Exception e) { e.printStackTrace(); } } }
实现步骤
1:判断表单 ServletFileUpload.isMultipartContent(req) 2:创建文件解析器 ServletFileIpload upload=new ServletFileUpload(new DiskFileItemFactory()) 3:解析请求 List<FileItem> list=upload.parseRequest() 4:迭代集合 for(FileItem item:list) 5:判断不是普通表单 !item.isFormFiled() 6:获取文件名,路径,文件后缀名 UUID uuid=UUID.randomUUUID(); String path=req.getSetvletContext().getRealPath("文件夹") String extension=FilenameUtils.getExtension(item.getName()) 7:写入文件 item.write(new File(path+"\\"+uuid+"."+extension))
文件类型判断
1:自定义异常类,自定义集合封装文件类型 2:判断为不支持类型时抛出异常信息 3:采用对应异常类型捕获继续抛出 4:将文件上传封装为工具类 5:捕获异常,将异常信息放到请求作用域中 6:使用请求转发返回初始页面,并使用EL表达式获取作用域中的值
文件下载
DownloadServlet
//获取参数 String filename = req.getParameter("filename"); //获取目录 String dir = getServletContext().getRealPath("WEB-INF/download"); //获取输出流 ServletOutputStream out = resp.getOutputStream(); //处理文件名称 中文乱码 resp.setHeader("Content-Disposition", "attachment; filename="+new String(filename.getBytes("UTF-8"),"ISO-8859-1")); //解决在IE6默认打开文件的方法 resp.setContentType("applicatoin/x-msdownload"); //创建文件 File f = new File(dir,filename); //拷贝文件 Files.copy(Paths.get(f.getAbsolutePath()), out);
download.jsp
<%@ page language="java" contentType="text/html; charset=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> <a href="/download?filename=xhr.zip">xhr.zip</a><br/> <a href="/download?filename=程序员.zip">程序员.zip</a> </body> </html>
默认为get请求,需要在server.xml文件中设置编码
<Connector port="80" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8"/>