servlet 实现下载文件
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>