首页 > 其他 > 详细

servlet 实现下载文件

时间:2016-01-05 20:53:07      阅读:119      评论:0      收藏:0      [点我收藏+]

servlet:

public class UpAndDownServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");
String type = request.getParameter("type");

if("down".equals(type)){
File file = new File("D:\\test\\44444.png");
FileInputStream is = new FileInputStream(file);
BufferedInputStream bs = new BufferedInputStream(is);
ServletOutputStream os = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
String date = new SimpleDateFormat("yyyy-HH-dd").format(new Date());
String fileName = date + ".jpg";
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
byte[] len = new byte[1024*2];
int read = 0;
while((read=is.read(len)) != -1){
bos.write(len, 0, read);
System.out.println("read---"+read);
}
bos.flush();
bos.close();
is.close();
}

}

}


怎样实现文件下载
要实现文件下载,我们仅仅须要设置两个特殊的对应头,它们是什么头?假设文件名称带中文,该怎样解决?
两个特殊的对应头:
----Content-Type:       application/octet-stream
----Content-Disposition: attachment;filename=aaa.zip
比如:
response.setContentType("image/jpeg");response.setHeader("Content- Disposition","attachment;filename=Bluehills.jpg");

页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>down</title>
  </head>
  <body>
    <form action="servlet/UpAndDownServlet?type=down" method="post">
    <input type="submit" value="下载">
    </form>
  </body>
</html>


servlet 实现下载文件

原文:http://www.cnblogs.com/bhlsheji/p/5103533.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!