- 超链接指向的资源如果能够被浏览器解析,则在浏览器中展示,如果不能解析,则弹出下载提示框。不满足需求
- 任何资源都必须弹出下载提示框
- 使用响应头设置资源的打开方式:
* content-disposition:attachment;filename=xxx
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/tomcatt/ds?filename=1.jpg">图片</a>
</body>
</html>
package servletcontext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;
@WebServlet("/ds")
public class DwonloadSerlvelet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取文件名称
String filename=request.getParameter("filename");
//2.使用字节输入流加载文件进入内存
//2.1先找到文件服务器路径
ServletContext sc=this.getServletContext();
String rp=sc.getRealPath("/img/"+filename);
//2.2用字节流关联
FileInputStream fis=new FileInputStream(rp);
//3.设置respose响应头
//3.1设置响应头类型:content-type
//获取文件的MIME类型
String mimeTYpe=sc.getMimeType(filename);
response.setHeader("content-type",mimeTYpe);
//3.2设置响应头打开方式:content-disposition
response.setHeader("content-disposition","attachment;filename"+filename);
//4.将输入流的数据写出到输出流中
ServletOutputStream sos= response.getOutputStream();
byte[] buff=new byte[1024*8];
int len=0;
while((len=fis.read(buff))!=-1){
sos.write(buff,0,len);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
解决中文文件名乱码问题
package cn.itcast.utils;
import sun.misc.BASE64Encoder;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class DownLoadUtils {
public static String getFileName(String agent, String filename) throws UnsupportedEncodingException {
if (agent.contains("MSIE")) {
// IE浏览器
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+", " ");
} else if (agent.contains("Firefox")) {
// 火狐浏览器
BASE64Encoder base64Encoder = new BASE64Encoder();
filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
} else {
// 其它浏览器
filename = URLEncoder.encode(filename, "utf-8");
}
return filename;
}
}