package com.mgj.hardware.platform.api.util;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class UrlFilesToZip {
public byte[] getImageFromURL(String urlPath) {
byte[] data = null;
InputStream is = null;
HttpURLConnection conn = null;
try {
URL url = new URL(urlPath);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setConnectTimeout(6000);
is = conn.getInputStream();
if (conn.getResponseCode() == 200) {
data = readInputStream(is);
} else {
data = null;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
}
return data;
}
public byte[] readInputStream(InputStream is) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = -1;
try {
while ((length = is.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
baos.flush();
} catch (IOException e) {
e.printStackTrace();
}
byte[] data = baos.toByteArray();
try {
is.close();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
public static void filesdown(HttpServletResponse response, List<String> urls) {
try {
String zipFileName = "robotLog_" + UUID.randomUUID().toString().substring(0, 7) + ".zip";
zipFileName = new String(zipFileName.getBytes(), StandardCharsets.UTF_8);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bos);
UrlFilesToZip s = new UrlFilesToZip();
for (String oneFile : urls) {
String suffix = oneFile.substring(oneFile.lastIndexOf("."));
zos.putNextEntry(new ZipEntry(System.currentTimeMillis() + suffix));
byte[] bytes = s.getImageFromURL(oneFile);
zos.write(bytes, 0, bytes.length);
zos.closeEntry();
}
zos.close();
response.setContentType("application/force-download");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + zipFileName);
OutputStream os = response.getOutputStream();
os.write(bos.toByteArray());
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@GetMapping("/platform/downloadLog")
@ApiOperation(value = "获取机器人日志", notes = "获取机器人日志")
public void downloadRobotLog(HttpServletResponse response) {
#如果前端没有传过来url集合,这部分处理获取url集合代码
UrlFilesToZip.filesdown(response, list);
}