通过浏览器下载文件(返回文件流)
- 下载文件到本地(下载文件,返回base64数据流,再将数据流转换为文件)
/**
* 批量下载附件
*/
public void batchDownloadDoc(HttpServletResponse response){
/**
* 批量下载文件路径
*/
public static final String DOWLOAD_FILE_PATH = "D:\\bathFile";
/**
* 将bathDocFile目录下的所有文件目录打包到d:/bathDocFile.zip
*/
public static final String BATH_FILE_PATH = "D:/bathFile";
//先删除临时存在的文件夹
FileUtils.deleteDirectory(Constants.BATH_FILE_PATH);
//通过fileId下载文件
FileVO download = fileService.download(fileId);
FileUtils.base64ToFile(download.getFileBase64(),download.getFileName());
//调用批量下载签名文件方法
this.downloadDataZip(response);
}
/**
* base64转换为文件,放入文件目录
* @param base64
* @param name
*/
public static void base64ToFile(String base64, String name) {
File file = null;
//创建文件目录
String filePath = Constants.DOWLOAD_FILE_PATH;
File dir = new File(filePath);
if (!dir.exists() && !dir.isDirectory()) {
dir.mkdirs();
}
BufferedOutputStream bos = null;
java.io.FileOutputStream fos = null;
try {
byte[] bytes = Base64.getDecoder().decode(base64);
file = new File(filePath + "\\" + name);
fos = new java.io.FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
log.error(e.getMessage());
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
log.error(e.getMessage());
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
}
/**
* 批量下载签名文件
*/
private void downloadDataZip(HttpServletResponse response) throws IOException {
//调用hutool的压缩zip文件的工具类(打包文件夹,压缩成ZIP文件,放入本地)
File zip = ZipUtil.zip(Constants.BATH_FILE_PATH);
InputStream inputStream = FileUtils.fileToInputStream(zip);
//调用文件下载方法
this.downloadFile(response, inputStream);
}
/**
* 下载文件流
*
* @param response
* @param inputData
* @throws IOException
*/
public void downloadFile(HttpServletResponse response, InputStream inputData) throws IOException {
//放到缓冲流里面
BufferedInputStream bins = new BufferedInputStream(inputData);
//获取文件输出IO流
OutputStream outs = response.getOutputStream();
BufferedOutputStream bouts = new BufferedOutputStream(outs);
response.setContentType("application/x-download");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("压缩文件", "UTF-8") + ".zip");
int bytesRead = 0;
byte[] buffer = new byte[8192];
//开始向网络传输文件流
while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
bouts.write(buffer, 0, bytesRead);
}
//这里一定要调用flush()方法
bouts.flush();
inputData.close();
bins.close();
outs.close();
bouts.close();
}
前端调用下载接口,直接浏览器下载压缩文件即可。