import org.apache.tools.zip.ZipOutputStream
import org.apache.tools.zip.ZipEntry
@ApiOperation(value = "下载文件链接")
@RequestMapping(value = "/getDownload", method = RequestMethod.POST)
public void downloadCERService(HttpServletResponse response) throws IOException {
String url = "";
ArrayList<String> strings = new ArrayList<>();
strings.add(url);
// 配置文件下载
response.setCharacterEncoding("UTF-8"); //设置编码字符
response.setContentType("application/octet-stream;charset=UTF-8");
//压缩包文件名
SimpleDateFormat fileZipName = new SimpleDateFormat("yyyyMMddhhmmss");
// 下载文件时候防止显示中文乱码 指定文件类型 .zip
response.setHeader("Content-Disposition", "attachment;filename=" +
URLEncoder.encode(fileZipName.format(new Date()) + ".zip", "UTF-8"));
getZipFile(getByte(strings), response.getOutputStream());
}
public static void getZipFile(Map<String, byte[]> stringByte, OutputStream outputStream) throws IOException {
//将文件打包成压缩文件
ZipOutputStream zipout = new ZipOutputStream(outputStream);
zipout.setEncoding("GBK"); //解决文件名中文乱码
Set<Map.Entry<String, byte[]>> dataEntrys = stringByte.entrySet();
for (Map.Entry<String, byte[]> data : dataEntrys) {
InputStream bufferIn = new BufferedInputStream(new
ByteArrayInputStream(data.getValue()));
byte[] bs = new byte[1024];
Arrays.fill(bs, (byte) 0);
//创建压缩文件内的文件
ZipEntry zipEntry = new ZipEntry(data.getKey())
zipout.putNextEntry(zipEntry);
//zipEntry.setUnixMode(755);//解决linux乱码
//zipEntry.setUnixMode(644);//解决linux乱码
int len = -1;
while ((len = bufferIn.read(bs)) > 0) {
zipout.write(bs, 0, len);
}
bufferIn.close();
}
try {
zipout.close();
} catch (IOException e) {
}
}
public static Map<String, byte[]> getByte(List<String> urlPath) {
Map<String, byte[]> stringMap = new HashMap<String, byte[]>();
byte[] data = new byte[1024];
ByteArrayOutputStream outputStream = null;
InputStream inputStream = null;
try {
for (String string : urlPath) {
//根据文件访问地址获取输入流
URL url = new URL(string);
URLConnection urlConnection = url.openConnection();
inputStream = urlConnection.getInputStream();
outputStream = new ByteArrayOutputStream();
int len = 0;
while ((len = inputStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
stringMap.put("2022.docx", outputStream.toByteArray());
}
return stringMap;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
Java 通过url下载文件并压缩
于 2022-11-18 21:11:59 首次发布