博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringMvc文件资源防止被外链链接
阅读量:7169 次
发布时间:2019-06-29

本文共 3139 字,大约阅读时间需要 10 分钟。

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 // 这个就是获取头部信息由这个来获取自己的头部信息

如果这个头部信息含有自己的域名则说明这个资源是自己的网站中的,否则则不让他进行下载

 

转载地址:http://vtmwm.baihongyu.com/

你可能感兴趣的文章
DNS配置
查看>>
MPLS ××× 互访关系控制
查看>>
如果说搞技术没前途,那是因为你技术搞的还不够深
查看>>
柳州市第一职业技术学校中心机房双活虚拟引擎容灾备份系统需求
查看>>
我的友情链接
查看>>
NV 3D viosn的设置
查看>>
在CentOS系统下安装Red5
查看>>
移动端消除click事件的延迟效果
查看>>
bgp与igp交互的配置
查看>>
[官方文档] oracle官方文档总汇(9i,10g,11gR1, 11gR2)
查看>>
宝马与F团合作能否再造营销奇迹?
查看>>
10 Linux程序包管理
查看>>
Exchange2010升级SP2 (包含各角色)
查看>>
实施Exchange 2013中的分层通讯簿
查看>>
Windows下安装MySql后,出现的错误解决办法
查看>>
oracle创建只读用户
查看>>
详解mysql的tee功能 并利用其记录相关操作
查看>>
Python function
查看>>
Linux系统中程序库文件简介
查看>>
基于Linux的集群系统(四) 实现过程之理论先导篇
查看>>