1 /** 2 * 文件下载防止文件被别的网站引用 3 * 直接访问会访问不了 4 * @Description: 5 * @param type 6 * 文件后缀名 7 * @param fileName 8 * 文件名 9 * @param request10 * @param response11 * @param referer12 * 转发头部里面只有包含您的域名才给资源13 * @return14 */15 // @RequestMapping(value="/downloadBySelf/{fileName}/{type}",method=RequestMethod.GET)16 @RequestMapping(value = "/downloadBySelf/{fileName}/{type}", method = RequestMethod.GET)17 public String downloadFileByself(@PathVariable("type") String type,18 @PathVariable("fileName") String fileName,19 HttpServletRequest request, HttpServletResponse response,20 @RequestHeader String referer // 这个就是获取头部信息21 ) {22 log.info(referer);23 if (referer != null) { //这里可以设置自己的域名24 // if(null!=referer&&referer.contains("?"))25 if (fileName != null) {26 String realPath = request.getServletContext().getRealPath(27 "WEB-INF/File/");28 File file = new File(realPath, fileName + "." + type);29 if (file.exists()) {30 response.setContentType("application/force-download");// 设置强制下载不打开31 response.addHeader("Content-Disposition",32 "attachment;fileName=" + fileName + "." + type);// 设置文件名33 byte[] buffer = new byte[1024];34 FileInputStream fis = null;35 BufferedInputStream bis = null;36 try {37 fis = new FileInputStream(file);38 bis = new BufferedInputStream(fis);39 OutputStream os = response.getOutputStream();40 int i = bis.read(buffer);41 while (i != -1) {42 os.write(buffer, 0, i);43 i = bis.read(buffer);44 }45 } catch (Exception e) {46 // TODO: handle exception47 e.printStackTrace();48 } finally {49 if (bis != null) {50 try {51 bis.close();52 } catch (IOException e) {53 // TODO Auto-generated catch block54 e.printStackTrace();55 }56 }57 if (fis != null) {58 try {59 fis.close();60 } catch (IOException e) {61 // TODO Auto-generated catch block62 e.printStackTrace();63 }64 }65 }66 }67 }68 }69 return null;70 }
@RequestHeader String referer // 这个就是获取头部信息由这个来获取自己的头部信息
如果这个头部信息含有自己的域名则说明这个资源是自己的网站中的,否则则不让他进行下载