javaEE_______Servlet_______简单下载功能实现
程序员文章站
2022-05-24 14:35:03
...
下载的分析:
下载可用两种方式实现
第一方式直接通过链接的方式实现:链接方式只能对浏览器不能识别额进行下载操作,(如index.html 浏览器就会自动解析显示而不是进行操作)
第二种通过代码的方式实现:所用文件都可以实现下载,
1、当链接提交到代码区后通过HttpServletRequest中的getParameter得到文件名
2、得到文件名后通过servletContext获得文件在计算机中的文件类型getMimeType()方法
3、设置Content-Type头response.setHeader("Content-Type",mimeType);
4、获得全路径this.getServletContext().getRealPath("/zy/"+fileName);
5、设置content-disposition:response.setHeader("Content-Disposition","attachment;filename="+fileName);
6、获得输入流InputStream is = new FileInputStream(realPath);
7、获得response的输出流:OutputStream os = response.getOutputStream();
如果有中文还要进行乱码解决
package com.pro.project.Web;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sun.misc.BASE64Encoder;
/**
* 文件下载处理
*/
public class downWeb extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName1 = request.getParameter("filename");
String fileName = new String(fileName1.getBytes("ISO-8859-1"),"UTF-8");
//获得文件名
String mimeType = this.getServletContext().getMimeType(fileName);
// 设置Content-Type头
response.setHeader("Content-Type",mimeType);
//设置文件的输入流
String realPath = this.getServletContext().getRealPath("/zy/"+fileName);
// 根据浏览器的类型处理中文文件的乱码问题:
String agent = request.getHeader("User-Agent");
System.out.println(agent);
if(agent.contains("Firefox")){
fileName = base64EncodeFileName(fileName);
}else{
fileName = URLEncoder.encode(fileName,"UTF-8");
}
//设置content-disposition:
response.setHeader("Content-Disposition","attachment;filename="+fileName);
InputStream is = new FileInputStream(realPath);
// 获得response的输出流:
OutputStream 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);
}
public static String base64EncodeFileName(String fileName) {//base64编码方式解决方法
BASE64Encoder base64Encoder = new BASE64Encoder();
try {
return "=?UTF-8?B?"
+ new String(base64Encoder.encode(fileName
.getBytes("UTF-8"))) + "?=";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>链接下载</h1>
<a href="/project/zy/day_login.rar">rar</a>
<a href="/project/zy/index.html">index</a>
<h2>代码下载</h2>
<a href="/project/downWeb?filename=蔡大爷.html">蔡</a>
</body>
</html>
上一篇: Servlet实现简单的下载图片
下一篇: Spring @Qualifier注解