本文共 1524 字,大约阅读时间需要 5 分钟。
·文件下载
Step1:需要通过HttpServletResponse.setContentType方法设置Content-type头字段的值,为浏览器无法使用某种方式或激活某个程序来处理的MIME类型,例如:"application/octet"或"application/x-msdownload"等、Step2:需要通过HttpServletResponse.setHeader方法设置Content-Disposition头的值为"attachment;filename=文件名"
Step:读取下载文件,调用HttpServletResponse.getOutputStream方法返回的OutputStream对象来向客户端写入附件内容。
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置请求的编码 request.setCharacterEncoding("UTF-8"); // 得到要下载的文件名 String fileName = request.getParameter("fileName"); // 得到文件存放咋服务器中的真实路径 String filePath = request.getServletContext().getRealPath("/upload/" + fileName); // 通过路径得到file对象 File file = new File(filePath); // 判断文件是否存在,并且是一个标准文件 if (file.exists() && file.isFile()) { // 设置相应类型 application/octet-stream response.setContentType("application/x-msdownload"); // 设置头信息 response.setHeader("Content-Disposition", "attachment;filename=" + fileName); // 得到文件的输入流 InputStream in = new FileInputStream(file); // 得到字节输出流 ServletOutputStream out = response.getOutputStream(); // 定义字节数组 和 长度 byte[] bytes = new byte[1024]; int len = 0; // 遍历 while((len = in.read(bytes)) != -1) { out.write(bytes, 0, len); } // 关闭资源 out.close(); in.close(); } else { System.out.println("文件不存在!"); } }
·超链接下载
1、超链接遇到浏览器无法识别的资源时,会自动下载; 2、超链接遇到浏览器能够识别的资源,则会直接显示; 3、如果想要让能够被识别的资源进行下载,则需要设置download属性 download属性: 规定浏览器进行下载。但有些浏览器并不支持。 download属性如果不设置值,则下载的文件名为默认文件名;如果设置了属性,则下载的文件名为download的属性值转载地址:http://qfgpb.baihongyu.com/