服务器端
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String filename=request.getParameter("filename");
System.out.println(filename);
String path=getServletContext().getRealPath("/");
String folder="upload/";
String z=path+folder+filename;
response.setHeader("Content-Disposition", "attachment;filename="+filename+"");//download 必须设置
File file=new File(z);
InputStream is=new FileInputStream(file);
OutputStream os=response.getOutputStream();
byte[] b=new byte[1024];
int len=0;
while((len=is.read(b))!=-1){
os.write(b, 0, len);
}
os.flush();
os.close();
is.close();
System.out.println("download success");
}
jsp
<a href="DownLoadSevlet?filename=${refFile}" >download</a> //retFile是后台request传来的文件名,如xxxx.mp4,或者自己写一个upload下存在的文件名称
web.xml
<servlet-name>DownLoadSevlet</servlet-name>
<servlet-class>test.DownLoadSevlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownLoadSevlet</servlet-name>
<url-pattern>/DownLoadSevlet</url-pattern>
</servlet-mapping>