前后端文件压缩(加密)下载
前端
前端使用$.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;
}