@WebServlet("/FileDown")
public class FileDown extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String file = request.getParameter("file"); //客户端传递的需要下载的文件名
String path = request.getServletContext().getRealPath("/img")+"/"+file; //默认认为文件在当前项目的根目录
System.out.println(path);
FileInputStream fis = new FileInputStream(path);
response.setCharacterEncoding("utf-8");
//attachment 附件--有附件为下载,无附件为预览
response.setHeader("Content-Disposition", "attachment; filename="+file);
ServletOutputStream out = response.getOutputStream();
byte[] bt = new byte[1024];
int length = 0;
//边读边写
while((length=fis.read(bt))!=-1){
out.write(bt,0,length);
}
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}