@ApiOperation("导出资料多个zip下载")
@RequestMapping(value = "/infoexportfiles", method = {RequestMethod.GET, RequestMethod.POST})
public void infoexportfiles(HttpServletResponse res,@ApiParam(value = "任务id")@RequestParam(value = "ids") String ids) {
log.info(" export url fiels and ids:" + ids);
try {
List<JSONObject> infoList = getInfoList(ids);
if (infoList.size() > 0) {
String fileName = URLEncoder.encode("resource.zip","UTF-8");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bos);
UrlFilesToZip s = new UrlFilesToZip();
for (JSONObject info : infoList) {
String path = info.getString("path");
if(StringUtils.isNotEmpty(path)){
String filename = info.getString("filename");
//请求地址
String oneFile = gateway+"/api/download?path="+path+"&fileName="+filename;
//下载文件名称
filename = filename.substring(0,filename.indexOf(".")) +"_"+System.currentTimeMillis()+ filename.substring(filename.indexOf("."));
zos.putNextEntry(new ZipEntry(filename));
byte[] bytes = s.getImageFromURL(oneFile);
zos.write(bytes, 0, bytes.length);
zos.closeEntry();
}
}
zos.close();
res.setContentType("application/force-download");// 设置强制下载不打开
res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
OutputStream os = res.getOutputStream();
os.write(bos.toByteArray());
os.close();
}
}catch(Exception e) {
e.printStackTrace();
}
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by 2019/11/28.
* 打包下载远程url文件
*/
public class UrlFilesToZip {
private static final Logger logger = LoggerFactory.getLogger(UrlFilesToZip.class);
//根据文件链接把文件下载下来并且转成字节码
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) {
logger.error("MalformedURLException", e);
} catch (IOException e) {
logger.error("IOException", e);
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
logger.error("IOException", e);
}
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) {
logger.error("IOException", e);
}
byte[] data = baos.toByteArray();
try {
is.close();
baos.close();
} catch (IOException e) {
logger.error("IOException", e);
}
return data;
}
}