本人技术有限,仅会使用window.location.href=prefix+“/downloads/ids?ids=”+arrays.toString()方式下载,传参时,注意url长度限制
前端代码
使用的是若依框架
<a class="btn btn-success" onclick="checkItem()">
class="fa fa-file"></i> 批量下载
</a>
使用 $.table.selectColumns("id");获取当前选中的id
function checkItem(){
var arrays = $.table.selectColumns("id");
判断是否选中列,没有选中则进行提示
arrays.length!=0?window.location.href=prefix+"/downloads/ids?ids="+arrays.toString() :alert("请至少选择一条数据");
}
后端代码
大概流程,每次获取id,需要将id对应的文件放到一个map中进行存储。然后统一进行输出。不要写在controller层中
/**
* 批量下载uploads
*/
@GetMapping("/downloads/ids")
@ResponseBody
public void uploads(@RequestParam(name = "ids") String ids ,HttpServletRequest request, HttpServletResponse response) {
String[] id = ids.split(",");
// 获取文件路径
List<Map> fileList = new ArrayList();
for (int i=0;i<id.length;i++) {
SysAttachment sysAttachment = new SysAttachment();
sysAttachment.setBusinessId(id[i]);
//查询文件所在位置
List<SysAttachment> list = iSysAttachmentService.selectSysAttachmentList(sysAttachment);
for (SysAttachment attachment: list){
Map map = new HashMap();
//获取文件生成时的姓名,我的是uuid.后缀
String fileName = attachment.getFileNameReal();
//获取文件真实时姓名
String nameShow = attachment.getFileNameShow();
//路径有问题,所以进行路径的替换
String filePaths =attachment.getFilePath().replaceAll("/profile/", "");
map.put("nameShow",nameShow);
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
//创建文件输入流
FileInputStream fis=new FileInputStream(filePaths+fileName);
BufferedInputStream bis=new BufferedInputStream(fis);
//字节输出流,注意要全部读取完成才能进行下一步
ByteArrayOutputStream baos=new ByteArrayOutputStream();
int c=bis.read();//读取bis流中的下一个字节
while(c!=-1){
baos.write(c);
c=bis.read();
}
bis.close();
byte retArr[]=baos.toByteArray();
map.put("outByte",retArr);
fileList.add(map);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
zipFiles(fileList,response);
}
//多个文件压缩成压缩包并下载
public void zipFiles(List<Map> fileList, HttpServletResponse httpResponse) {
try(ZipOutputStream zipOutputStream = new ZipOutputStream(httpResponse.getOutputStream()); OutputStream out =null) {
//下载压缩包
httpResponse.setContentType("application/zip");
httpResponse.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("随便.zip", "UTF-8"));
// 创建 ZipEntry 对象
for (Map map:fileList){
ZipEntry zipEntry = new ZipEntry((String) map.get("nameShow"));
zipOutputStream.putNextEntry(zipEntry);
zipOutputStream.write((byte[]) map.get("outByte"));
}
} catch (IOException e) {
//日志输出
log.error(e.getMessage(), e);
}
}
图片如下