public class DownLoadServlet extends HttpServlet { FileInputStream fis = null; ServletOutputStream sos = null; //向浏览器输出消息 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { //1.文件在服务器器路径 String filePath = "D:\\Wallpaper\\wallhaven-2krvvx.png"; //2.获取文件名称 String fileName = filePath.substring(filePath.lastIndexOf("\\")+ 1); //3.让浏览器支持我们需要下载的东西 resp.setHeader("content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8")); //4.获取下载的文件流 fis = new FileInputStream(filePath); //5.创建缓冲区 byte[] b = new byte[1024]; //获取响应(response对象) 的输出流(关键步骤) // 因为文件要响应到客户端,所以这个输出流要从response对象获取! sos = resp.getOutputStream(); //将文件流写入缓冲区 while (fis.read(b) > -1){ //将文件读出,文件写出的文件地址即浏览器默认下载地址(设置) sos.write(b); } }catch (Exception e){ e.printStackTrace(); }finally { //关闭流 sos.close(); fis.close(); } } }
浙公网安备 33010602011771号