直接傳入地址下載
public static void downloadFile(HttpServletResponse response, String url) {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/octet-stream");
response.setHeader("content-type", "application/octet-stream");
String fileName = url.substring(url.lastIndexOf("/") + 1);
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
InputStream in = null;
OutputStream out = null;
try {
//獲取要下載的文件輸入流
in = new URL(url).openStream() ;
int len = 0;
//創(chuàng)建數(shù)據(jù)緩沖區(qū)
byte[] buffer = new byte[1024];
//通過response對象獲取outputStream流
out = response.getOutputStream();
//將FileInputStream流寫入到buffer緩沖區(qū)
while ((len = in.read(buffer)) > 0) {
//使用OutputStream將緩沖區(qū)的數(shù)據(jù)輸出到瀏覽器
out.write(buffer, 0, len);
}
out.flush();
in.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
將多個(gè)文件打包成zip流下載
public static void downloadFile2Zip(HttpServletResponse response, List<String> urls, String zipFileName) {
if (CollectionUtil.isNotEmpty(urls) && !StringUtils.hasLength(zipFileName)) {
throw new RuntimeException("數(shù)據(jù)為空");
}
String dowwnloadName = zipFileName + ".zip";
response.setCharacterEncoding("UTF-8");
response.setContentType("application/octet-stream");
response.setHeader("content-type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(dowwnloadName, StandardCharsets.UTF_8));
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
zipOut.setMethod(ZipOutputStream.DEFLATED);
for (String url : urls) {
try (InputStream is = new URL(url).openStream()) {
String fileName = url.substring(url.lastIndexOf("/") + 1);
if (!fileName.isEmpty()) {
zipOut.putNextEntry(new ZipEntry(fileName));
final byte[] bytes = new byte[1024];
int lenth;
while ((lenth = is.read(bytes)) != -1) {
zipOut.write(bytes, 0, lenth);
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者