Commons组件实现文件上传与下载
一、文件上传
所需jar包
首先是commons-fileupload.jar包
其次是commons-IO.jar包
前者的使用依赖后者,两者缺一不可
实现
前台要求
在前台提交的form表单请求方式必须为:post,编码类型需设置为:multipart/form-data
后台实现
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart) {//判断前台请求form表单的编码类型是否为multipart/form-data
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);//解析请求,获取form表单所提交的每一项
for(FileItem item:items) {
if(!item.isFormField()) {//判断是否为普通form表单项,若不普通,则认为是文件,进行上传操作
String fileName = item.getName();//获取文件名
String path = "D:\\MyDevelope\\ServerFiles";//设置文件在服务器中的存储路径
File file = new File(path,fileName);
item.write(file);//将文件写入指定路径
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
二、文件下载
于文件上传所不同的是,文件下载不需要导包,但是他需要解决中文乱码问题
解决中文乱码
对于Firefox、opera、chrome,可以将content-Disposition消息头设置为:
response.addHeader("content-Disposition","attachment;filename==?UTF-8?B?"+new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))+"?=");
而对于edge,则需要将content-Disposition消息头设置为:
response.addHeader("content-Disposition","attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));
获取客户端浏览器类型
可以使用
request.getHeader("User-Agent");
获取包含浏览器类型的消息头,接下来使用String的contains()方法即可判断客户端是否为某种类型
实现
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.addHeader("content-Type", "application/octet-stream");//设置下载的文件的MIME类型
String fileName = request.getParameter("fileName");
String path = "D:\\MyDevelope\\ServerFiles\\";//设置要下载的文件在服务器中的目录
/**
*解析浏览器类型,设置不同的“content-Disposition”消息头来解决中文乱码问题
*/
String agent = request.getHeader("User-Agent").toLowerCase();
String contentDisposition = "attachement;filename="+fileName;
System.out.println(agent);
if(agent.contains("edge")) {
System.out.println("edge");
contentDisposition = "attachment;filename="+URLEncoder.encode(fileName,"UTF-8");
}else if(agent.contains("firefox")||agent.contains("opr")||agent.contains("chrome")) {
contentDisposition = "attachment;filename==?UTF-8?B?"+new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))+"?=";
}
response.addHeader("content-Disposition",contentDisposition);
//InputStream in = getServletContext().getResourceAsStream(path+fileName);//此种方式只能下载项目根目录中的文件
/**
* 通过IO操作将文件输出给用户
*/
InputStream in = new FileInputStream(path+fileName);
ServletOutputStream out = response.getOutputStream();
byte[] bs = new byte[10];
int len = -1;
while((len=in.read(bs))!=-1) {
out.write(bs,0,bs.length);
}
out.close();
in.close();
}