//这个是servlet 代码
import java.io.FileInputStream;
import java.io.IOException;
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.FileInputStream;
import java.io.IOException;
/**
* Servlet implementation class imgservlet
*/
@WebServlet("/imgservlet")
public class imgservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public imgservlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filename=request.getParameter("filename");//获取要下载文件名称
System.out.println(filename);
ServletContext context=this.getServletContext();//获取context对象
String realpath=context.getRealPath("/img/"+filename);//获取文件位置
System.out.println(realpath);
FileInputStream fis=new FileInputStream(realpath);//用字节流关联
String mimeType=context.getMimeType(filename);//获取文件的mime类型
System.out.println(mimeType);
response.setHeader("content-type", mimeType);//设置文件类型为mimetype
//解决中文乱码问题
String agent=request.getHeader("user-agent");//获取user-aget请求头
System.out.println(agent);
filename=DownLoadUtils.getFileName(agent, filename);//使用工具类方法设置编码
response.setHeader("content-disposition","attachment;filename="+filename);
//将数据写入流中
ServletOutputStream sos=response.getOutputStream();
byte [] buff=new byte[1024 * 8];
int len=0;
while ((len=fis.read(buff))!=-1) {
sos.write(buff, 0, len);
}
fis.close();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
//解决中文乱码的工具类网上多的很
package cout.pring;
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;
}
}
jsp代码
<a href="imgservlet?filename=1.jpg">图片2</a>
<a href="imgservlet?filename=scc.mp4">视频2</a>
这里利用filename之间给值来进行区别下载但是要注意文件的路径问题很多时候都是文件路径有问题