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+"/";
%>



 
   
    down
 
 
   

   
   

 


你可能感兴趣的:(Java)