servlet实现文件下载
程序员文章站
2022-05-24 14:38:36
...
public void execute(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/download");
String filename=request.getParameter("fileName");
String sourceName= filename;
filename=new String(filename.getBytes("UTF-8"),"ISO8859-1");
response.addHeader("content-Disposition", "attachment;filename=\"" + filename + "\"");
InputStream in =new FileInputStream(request.getServletContext().getRealPath("upload/" + sourceName));
ServletOutputStream out = response.getOutputStream();
byte[] buf=new byte[1024];
int len=-1;
while((len=in.read(buf, 0, buf.length))!=-1){
out.write(buf, 0, len);
out.flush();
}
in.close();
out.close();
}