WEB项目中的三种下载方式

超链接下载

  • 编码特别简单
  • 有些类型的文件(jpg,gif,png,txt,html)会直接在浏览器打开
  • 一般用在对压缩包的下载
   <a href="${pageContext.request.contextPath}/139-150921162931.jpg">jpga><br/>
   <a href="${pageContext.request.contextPath}/20170808225541.zip">zipa><br/>
   <a href="${pageContext.request.contextPath}/中文.zip">zipa>
    

io流

  • 设置响应头,通知浏览器以下载的方式打开
    • key=Content-Disposition
    • value=attachment;filename=+fname
  • 可以灵活的自定义开发下载的内容,添加断点续传等功能
  • 代码相对复杂
//通知服务器以utf-8 接收
response.setContentType("text/html;charset=utf-8");

String name = request.getParameter("name");
//去除中文乱码
name=new String(name.getBytes("iso-8859-1"),"utf-8");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(getServletContext().getRealPath(name)));
System.out.println(getServletContext().getRealPath(name)); 
//火狐无法解决下载乱码问题
name= URLEncoder.encode(name,"utf-8");

//通知服务器以下载方式打开文件
response.setHeader("Content-Disposition", "attachment;filename="+name);

BufferedOutputStream bos= new BufferedOutputStream(response.getOutputStream());
int len=-1;
while((len=bis.read())!=-1){
bos.write(len);
}
System.out.println("写出完毕");

文件转发的方式

  • 设置响应头和io流方式相容
  • 代码相对简单,可以让所有格式的文件直接以附件下载的方式打开
  • 不够灵活
  • forward转发即可
    示例
response.setContentType("text/html;charset=utf8");
String name = request.getParameter("name");
name = new String(name.getBytes("iso-8859-1"), "utf-8");
response.setHeader("Content-Disposition",
    "attachment;filename="+ URLEncoder.encode(name,"utf-8")); //中文依旧乱码
request.getRequestDispatcher(name).forward(request, response);

测试用index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$title>
  head>
  <body>
    <h1>1.超链接下载方式h1>
    <a href="${pageContext.request.contextPath}/139-150921162931.jpg">jpga><br/>
    <a href="${pageContext.request.contextPath}/20170808225541.zip">zipa><br/>
    <a href="${pageContext.request.contextPath}/中文.zip">中文zipa>
    <h1>2.io流下载方式h1>
    <a href="${pageContext.request.contextPath}/demo1?name=139-150921162931.jpg">jpga><br/>
    <a href="${pageContext.request.contextPath}/demo1?name=20170808225541.zip">zipa><br/>
    <a href="${pageContext.request.contextPath}/demo1?name=中文.zip">中文zipa>
    <h1>3.转发形式下载h1>
    <a href="${pageContext.request.contextPath}/demo2?name=139-150921162931.jpg">jpga><br/>
    <a href="${pageContext.request.contextPath}/demo2?name=20170808225541.zip">zipa><br/>
    <a href="${pageContext.request.contextPath}/demo2?name=中文.zip">中文zipa>
  body>
html>

ps: 火狐中文乱码问题 解决办法:
http://blogs.msdn.com/b/ieinternals/archive/2010/06/07/content-disposition-attachment-and-international-unicode-characters.aspx

http://stackoverflow.com/questions/93551/how-to-encode-the-filename-parameter-of-content-disposition-header-in-http

http://greenbytes.de/tech/tc2231/

你可能感兴趣的:(java,web,jsp,下载文件,浏览器,编码)