码迷,mamicode.com
首页 > 其他好文 > 详细

servlet 实现下载文件

时间:2014-06-18 06:24:27      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:style   class   java   http   ext   color   

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 实现下载文件,布布扣,bubuko.com

servlet 实现下载文件

标签:style   class   java   http   ext   color   

原文地址:http://blog.csdn.net/j04110414/article/details/31775993

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!