java 前后端文件压缩加密下载

前后端文件压缩(加密)下载

前端

前端使用$.ajax不支持文件流的下载,后端传输的流会变成乱码的格式,解压文件受损,在不使用axios的情况下,可以通过直接对文件路径进行访问的形式进行前段自定义下载。

$.post{host+'/data/jar',data,{headers:{'Content-type':'application/json'}}).then(res => {window.location.href = hostUrl +'/data/zip'})

后端

后端可以通过将文件压缩下载,保存文件,前端通过调用文件路径显示前端自定义下载

1、导入zip4j 包

<dependency>
    <groupId>net.lingala.zip4j</groupId>
    <artifactId>zip4j</artifactId>
    <version>1.3.2</version>
</dependency>

2、压缩文件

public class CreatePasswordProtectedZipExample{
	public static void encrypt_zip(String src_file,String passWord){
		File file = new File(src_file);
		ZipParameters parameters = new ZipParameters();
		parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);//压缩方式
		parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);//压缩级别
		if(passWord != null){
			parameters.setEncryptFiles(true);
			parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);//加密方式
			parameters.setPassword(encode.toCharArray());//设置密码
		}
		try{
		ZipFile zipFile = new ZipFile(src_file+'.zip');
		zipFile.setFileNameCharset("gbk");
		zipFile.addFolder(file,parameters);
		}catch(ZipException e){
		e.printStackTrace();}
	}
}

3、将文件转换成流传给前端

public File outPutZip(HttpServletResponse response) throws IOException{
	String filepath = PlantformPropertiesSingleton.getInstance().getConfigValueInProperties("sys-properties")//定义的常量
	File file = new File(filepath+".zip");
	BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
	byte[] buf = new byte[1024];
	int len = 0;
	response.reset();//传输建立
	response.setContentType("application/x-msdownload");
	response.setHeader("Content-Disposition","attachment;filename="+file.getName());
	OutputStream out = response.getOutputStream();
	while((len = br.read(buf))>0)
		out.write(buf,0,len);
	br.close();
	out.close();
	file.delete();
	return file;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值