web下载
编写Servlet启动Tomcat实现在web网页下载文件
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String realPath="D:\\ideaworkplace\\JAVAWEB01\\response\\src\\main\\resource\\jinghua.mp4";
System.out.println("下载路径:"+realPath);
String fileName=realPath.substring(realPath.lastIndexOf("\\")+1);
resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
FileInputStream in = new FileInputStream(realPath);
int len=0;
byte [] buffer=new byte[1024];
ServletOutputStream out=resp.getOutputStream();
while((len=in.read(buffer))>0){
out.write(buffer,0,len);
}
in.close();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
如图所示
|