Springboot生成一个加密下载链接

spring生成一个普通下载链接

由于工作需要,要做一个能够提供给用户的下载链接,使用户可以直接下载从服务器上直接下载文件,由于有多个用户,所以不能让别人看到彼此的路径,进行了加密处理

Controller层代码

项目搭建这里直接省去,可以直接看controller代码

     /**
	 /**
	 * @param 文件名称
	 * @param 文件路径
	 * @return
	 */
	@RequestMapping(value = "Zip/DownUrl", method = RequestMethod.GET, produces ="application/json;charset=UTF-8")
    @ResponseBody
	public Object downZip(@RequestParam(value="company",required = true)String company,
			@RequestParam(value="path",required = true)String path){
	       ResponseEntity<InputStreamResource> response = null;
	       EncryptionInfo encry = new EncryptionInfo();
	       String companyname = encry.decodeBack(company);
	       String filepath = encry.decodeBack(path);
	       logger.info(companyname+"开始下载,下载路径:"+filepath);
	        try {
	            response = ExcelUtil.download(filepath, companyname, companyname);
	        } catch (Exception e) {
	            logger.error("下载文件失败");
	        }
	        return response;
	}

只需要传入文件的绝对路径和文件名称外部调用即可

EncryptionInfo加密代码

package com.example.excelutil;

import java.io.UnsupportedEncodingException;

public class EncryptionInfo {
	
	
	
	 /**
     * 十六进制转中文字符串
     */
    public static String decodeBack(String str) {
        if ( str == null ) {
            return "转换失败";
        }
        byte[] s = pack(str); //十六进制转byte数组
        String gbk;
        try {
            gbk = new String(s, "gbk"); //byte数组转中文字符串
        } catch ( UnsupportedEncodingException ignored ) {
            gbk = "转换失败";
        }
        return gbk;
    }
    
    /**
     * 十六进制转byte数组
     */
    public static byte[] pack(String str) {
        int nibbleshift = 4;
        int position = 0;
        int len = str.length() / 2 + str.length() % 2;
        byte[] output = new byte[len];
        for (char v : str.toCharArray()) {
            byte n = (byte) v;
            if (n >= '0' && n <= '9') {
                n -= '0';
            } else if (n >= 'A' && n <= 'F') {
                n -= ('A' - 10);
            } else if (n >= 'a' && n <= 'f') {
                n -= ('a' - 10);
            } else {
                continue;
            }
            output[position] |= (n << nibbleshift);
            if (nibbleshift == 0) {
                position++;
            }
            nibbleshift = (nibbleshift + 4) & 7;
        }
        return output;
    }
    
    
    /**
     * 中文字符串转十六进制
     */
    public static String decodeLock(String str) {
        if ( str == null ) {
            return "转换失败";
        }
        String gbk;
        try {
            byte[] sss = str.getBytes("GBK");  //中文字符串转byte数组
            gbk = unpack(sss); // byte数组转十六进制
        } catch ( Exception E ) {
            gbk = "转换失败";
        }
        return gbk;
    }
    
    
    /**
     * byte数组转十六进制,模拟php中unpack
     */
    public static String unpack(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        for (int i = 0; i < bytes.length; i++) {
            int v = bytes[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
    
   public static void main(String[] args) {
		System.out.println(decodeLock("黑龙江分公司.zip"));
		System.out.println(decodeLock("D:\\SpringWork\\ExcelDataUtil\\war"));
		System.out.println(decodeBack("badac1fabdadb7d6b9abcbbe2e7a6970"));
		System.out.println(decodeBack("443a5c537072696e67576f726b5c457863656c446174615574696c5c776172    "));
	}
}
控制台输出:
badac1fabdadb7d6b9abcbbe2e7a6970
443a5c537072696e67576f726b5c457863656c446174615574696c5c776172
黑龙江分公司.zip
D:\SpringWork\ExcelDataUtil\war	


加密如有疑惑,可参考https://www.cnblogs.com/heqiyoujing/p/9303291.html这篇文章,我也是这个博客里面看的,感谢

ExcelUtil.download方法

创建ExcelUtil类,撰写downLoad方法

 public static final String separator = File.separator;

 /**
     * @param filePath 文件目录
     * @param fileName 文件名称
     * @param newName  下载文件名
     * @return 
     */
    public static ResponseEntity<InputStreamResource> download(String filePath, String fileName, String newName) {
        String path = null;
        ResponseEntity<InputStreamResource> response = null;
        try {
            path = filePath + separator + fileName;            
            InputStream inputStream =new FileInputStream(path);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition",
                    "attachment; filename="
                            + new String(newName.getBytes("gbk"), "iso8859-1"));
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            response = ResponseEntity.ok().headers(headers)
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new InputStreamResource(inputStream));
        } catch (FileNotFoundException e1) {
            logger.error("找不到指定的文件路径", e1);
        } catch (IOException e) {
            logger.error("获取不到文件IO", e);
        }
        return response;
    }

结束

到这里就结束了,访问

http://localhost:8081/Zip/DownUrl?company=badac1fabdadb7d6b9abcbbe2e7a6970&path=443a5c537072696e67576f726b5c457863656c446174615574696c5c776172

在这里插入图片描述
localhost问本地路径,要是不对记得更改哦!
实际应用服务端生成这个加密的下载链接,发送个客户端用户,客户端用户点击进行下载,有任何问题即时和我留言

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值