当前位置:网站首页>批量下载文件----压缩后再下载
批量下载文件----压缩后再下载
2022-04-23 03:17:00 【数学教师写BUG】
把所需要的的附件全部下载下来放在指定的位置,然后对此位置上的附件全部打包成压缩文件,然后再下载下来。方便用户查看。
public IZrarResponse downloadZdxjr(IZrarRequest req) throws ParseException, ParseException, IOException {
IZrarResponse res = new ZrarResponse();
List list = "具体的获取数据的方法---需要根据项目需求写";
String oid = "";//这三个是项目所需要的值
String wjmc = "";
String unitname = "";
String url = null;
JsonResult<FileObject> result = new JsonResult();
//从系统配置文件获取路径位置
String realPath0 = PropertyManager.getProperty("CommonUploadFileUrl", new String[0]);
String realPath = realPath0.replace("\\", "/");
if (realPath.lastIndexOf("/") == realPath.length() - 1) {
realPath = realPath + "ssfa/";
} else {
realPath = realPath + "/ssfa/";
}
//要是文件路径已存在则删除再新建
File f = new File(realPath);
if (f.exists()) {
FileUtils.deleteDirectory(f);
f.mkdirs();
} else {
f.mkdirs();
}
for (int i = 0; i < list.size(); i++) {
Map map = (Map) list.get(i);
oid = (String) map.get("oid");
wjmc = (String) map.get("wjmc");
unitname = (String) map.get("unitname");
if (StringUtil.isNull(oid)) {
result.setErrorMsg("oid can not be null");
return res.addResHtml(result.toJson());
}
HttpServletRequest request = req.getHttpServletRequest();
//获取地址请求下载附件
url = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/oss/download/" + oid + "?direct=1";
//获取附件信息
getFile(url, "(" + unitname + ")" + wjmc, realPath);
}
String currentTime = DateUtils.getCurrentTime();
currentTime = currentTime.replaceAll("-", "").replaceAll(" ", "").replaceAll(":", "");
//压缩文件
compressToZip(realPath, realPath0, "实施方案" + currentTime + ".zip");
//下载压缩后的文件
res.addStream(new File(realPath0 + "实施方案" + currentTime + ".zip"));
return res;
}
/**
* @Description : 获取附件文件 并写入指定位置
* @Author:
* @Date: 2022/4/22 15:42
*/
private boolean getFile(String urlstr, String filename, String filepath) {
InputStream in = null;
HttpURLConnection conn = null;
FileOutputStream os = null;
try {
URL url = new URL(urlstr);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(5000);
conn.setReadTimeout(60000);
in = conn.getInputStream();
os = new FileOutputStream(filepath + filename);
byte[] buf = new byte[8 * 1024];
int len;
while ((len = in.read(buf)) != -1) {
os.write(buf, 0, len);
}
os.flush();
if (os instanceof FileOutputStream) {
((FileOutputStream) os).getFD().sync();
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
}
}
if (null != conn) {
conn.disconnect();
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
}
}
/**
* @param sourceFilePath 源文件路径
* @param zipFilePath 压缩后文件存储路径
* @param zipFilename 压缩文件名
* @Description :压缩文件
* @Author:
* @Date: 2022/4/22 15:48
*/
public static void compressToZip(String sourceFilePath, String zipFilePath, String zipFilename) {
File sourceFile = new File(sourceFilePath);
File zipPath = new File(zipFilePath);
if (!zipPath.exists()) {
zipPath.mkdirs();
}
File zipFile = new File(zipPath + File.separator + zipFilename);
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
writeZip(sourceFile, "", zos);
// 文件压缩完成后,删除被压缩文件
// boolean flag = deleteDir(sourceFile);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e.getCause());
}
}
/**
* @param file 源文件目录
* @param parentPath 压缩文件目录
* @param zos 文件流
* @Description : 遍历所有文件,压缩
* @Author:
* @Date: 2022/4/22 15:49
*/
public static void writeZip(File file, String parentPath, ZipOutputStream zos) {
if (file.isDirectory()) {
// 目录
parentPath += file.getName() + File.separator;
File[] files = file.listFiles();
for (File f : files) {
writeZip(f, parentPath, zos);
}
} else {
// 文件
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
// 指定zip文件夹
ZipEntry zipEntry = new ZipEntry(parentPath + file.getName());
zos.putNextEntry(zipEntry);
int len;
byte[] buffer = new byte[1024 * 10];
while ((len = bis.read(buffer, 0, buffer.length)) != -1) {
zos.write(buffer, 0, len);
zos.flush();
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e.getCause());
}
}
}
版权声明
本文为[数学教师写BUG]所创,转载请带上原文链接,感谢
https://blog.csdn.net/u011271164/article/details/124348505
边栏推荐
- 2022年P气瓶充装培训试题及模拟考试
- The most detailed in the whole network, software testing measurement, how to optimize software testing cost and improve efficiency --- hot
- 《C语言程序设计》(谭浩强第五版) 第9章 用户自己建立数据类型 习题解析与答案
- Queue storage and circular queue
- Using stack to solve the problem of "mini parser"
- Xamarin effect Chapter 21 expandable floating operation button in GIS
- A set of C interview questions about memory alignment. Many people make mistakes!
- Mysql database, inconsistent index character set, slow SQL query, interface timeout
- C introduction of variable parameter params
- 软件测试相关知识~
猜你喜欢
Due to 3 ²+ four ²= five ², Therefore, we call '3,4,5' as the number of Pythagorean shares, and find the array of all Pythagorean shares within n (including n).
IDEA查看历史记录【文件历史和项目历史】
Experiment 5 components and event handling
The most easy to understand dependency injection and control inversion
Maui initial experience: Cool
svg标签中利用<polygon/>循环数组绘制多边形
为什么BI对企业这么重要?
Mise en service PID du moteur de codage (anneau de vitesse | anneau de position | suivant)
Drawing polygons with < polygon / > circular array in SVG tag
It can receive multiple data type parameters - variable parameters
随机推荐
Node configuration environment CMD does not take effect
yes. Net future
C syntax sugar empty merge operator [?] And null merge assignment operator [? =]
Queue storage and circular queue
OLED multi-level menu record
二进制文件版本控制工具选择难?看完这篇你会找到答案
EasyUI's combobox implements three-level query
[Mysql] LEFT函數 | RIGHT函數
[new version release] componentone added Net 6 and blazor platform control support
通过 zxing 生成二维码
svg标签中利用<polygon/>循环数组绘制多边形
If the deep replication of objects is realized through C #?
ASP. Net 6 middleware series - conditional Middleware
be based on. NETCORE development blog project starblog - (1) why do you need to write your own blog?
Mysql database design specification
PID debugging of coding motor (speed loop | position loop | follow)
How to achieve centralized management, flexible and efficient CI / CD online seminar highlights sharing
Tencent video VIP member, weekly card special price of 9 yuan! Tencent official direct charging, members take effect immediately!
Use DFS to solve the problem of "number of dictionary rows"
软件测试相关知识~