下载单个文件和压缩包下载demo对比
下载压缩包:
public String downZip(List<String> fileUrls, HttpServletResponse response) {
logger.info("批量下载的地址有:{}",JSON.toJSONString(fileUrls));
ZipOutputStream zipStream = null;
response.setContentType("application/force-download");
response.addHeader("Content-Disposition","attachment;filename=file.zip");
OutputStream os = null;
InputStream fis = null;
HttpURLConnection conn = null;
try{
os = response.getOutputStream();
zipStream = new ZipOutputStream(os);
for(String filePath : fileUrls){
URL path = new URL(filePath);
conn = (HttpURLConnection) path.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
fis = conn.getInputStream();// 通过输入流获取数据
ZipEntry zipEntry = new ZipEntry(filePath.substring(filePath.lastIndexOf("/")));
zipStream.putNextEntry(zipEntry);
int read = 0;
byte[] buf = new byte[1024 * 10];
while((read = fis.read(buf)) != -1)
{
zipStream.write(buf, 0, read);
}
}
}catch (Exception e){
logger.info("批量下载失败,异常:{}",e.getMessage());
e.printStackTrace();
}finally {
streamClose(zipStream);
streamClose(bufferedInputStream);
streamClose(os);
streamClose(fis);
}
return null;
}
private void streamClose(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
下载单个:
HttpURLConnection conn = null;
try {
File file = new File(filePath);
// 取得文件的后缀名。
String ext = file.getName().substring(file.getName().lastIndexOf(".") + 1).toLowerCase();
StringBuffer buffername = new StringBuffer(filePath.substring(filePath.lastIndexOf("/")+1));
String filename = buffername.toString();
URL path = new URL(filePath);
conn = (HttpURLConnection) path.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream fis = conn.getInputStream();// 通过输入流获取数据
byte[] buffer = readInputStream(fis);
if (null != buffer && buffer.length > 0) {
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String((filename).getBytes("GBK"), "ISO8859_1"));
response.addHeader("Content-Length", "" + buffer.length);
OutputStream toClient = response.getOutputStream();
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return null;