由于经常需要从文件存储服务器取出文件,并提供压缩并下载这个功能,简单记录一下
建立一个临时文件夹
String tempDirPath = FilenameUtils.concat(FileUtils.getTempDirectory().getPath(), UUID.randomUUID().toString());
File dir = new File(tempDirPath);
if (!dir.exists()) {
dir.mkdir();
}
从服务器下载文件并存储在文件夹中
try (InputStream inputStream = dataStorage.getInputStream(wsxx.getWjlj())) {
File file = new File(FilenameUtils.concat(tempDirPath, wsxx.getWjmc()));
FileUtils.copyInputStreamToFile(inputStream, file);
} catch (StoreSystemException | IOException e) {
log.error("{}文件下载失败", wsxx.getWjmc(), e);
}
进行压缩
// 该outputStream 是由HttpServletResponse 带出来的
try (ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream)) {
toZip(dir, zipOutputStream);
} catch (IOException e) {
log.error("压缩文件失败", e);
}
private void toZip(File sourceFile, ZipOutputStream zos) throws IOException {
File[] files = sourceFile.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
try (FileInputStream in = new FileInputStream(file)) {
zos.putNextEntry(new ZipEntry(file.getName()));
IOUtils.copy(in, zos);
} catch (IOException e) {
log.error("压缩文件失败", e);
} finally {
zos.closeEntry();
}
}
}
}
controller层
@PostMapping("downloadWs")
public void downloadWs(@RequestBody WsDownloadVO wsDownloadVO, HttpServletResponse response) {
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("application/zip;charset=utf-8");
try {
response.flushBuffer();
pljsService.downloadWs(wsDownloadVO.getXyrbh(), wsDownloadVO.getGarybh(), response.getOutputStream());
} catch (IOException e) {
log.error("获取文件下载输出流失败", e);
}
}
前端接收代码
downloadWs: function () {
var _this = this
var fileName = "文书.zip";
Artery.axios.post("ui/pljs/downloadWs", {'xyrbh': _this.xyrbh, 'garybh': _this.garybh}, {responseType: 'arraybuffer'}).then(function (res) {
var blob = new Blob([res.data], {type: 'application/zip;charset=utf-8'})
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, fileName);
} else {
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
}
})
}
零零碎碎就这些吧