SpringBoot+Vue+Element-ui实现文件批量下载功能
一、前端准备工作
1.创建一个el-button按钮用来触发下载操作
<el-button type="success" @click="saveMultiple()">批量下载</el-button>
2.在table中使用@selection-change="selectionChange"来获取被选中的行的数据
<elian-grid
ref="table"
:data="tableData"
:loading="gridLoading"
:page-size="pageSize"
:page-sizes="pageSizes"
:current-page="currentPage"
:total="total"
height="500"
resize
@selection-change="selectionChange"
>
<el-table-column type="selection"></el-table-column>
</elian-grid>
3.在vue的data中和method中定义参数和执行函数
vue发送下载请求时需要定义responseType:'blob',(一般还要在请求头中定义'Authorization': getToken(),getToken()为自定义方法,需要自己去写。)
//引用axios
import axios from 'axios'
data() {
return {
// 表格选中的数据,用数组来接收
multipleSelection: [],
}
},
methods: {
selectionChange(val) {
//用数组接收所有选中行的ID
val.forEach((e) => {
this.multipleSelection.push(e.attrId)
})
},
saveMultiple() {
if (this.multipleSelection.length <= 0) {
this.$message({
type: 'warning',
message: '请选中附件'
})
return
}
axios({
method: "post",
responseType: 'blob',
url: "/api/attach/saveMultipleFun",
headers: {
'Authorization': `${getToken()}`
},
withCredentials: true,
data: data
}).then((res) => {
// res就是接口返回的文件流了
let blob = new Blob([res.data], { type: "application/zip" });
let objectUrl = URL.createObjectURL(blob);
window.location.href = objectUrl;
});
}
}
到此为止,前端部分就准备好了
二、Java后端模块代码
1.附件DTO
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
/**
* <p>
* 附件 dto
* </p>
*
* @author KanShufan
* @since 2021-07-12 14:11
*/
@Data
public class AttachDTO extends Page<AttachDTO> {
/**
* 所属记录
*/
private String targetId;
/**
* 所属模块
*/
private Integer moudleType;
/**
* 详细模块
*/
private Integer detailType;
/**
* 附件名称
*/
private String originName;
/**
* 新增人id
*/
private String addUserId;
/**
* 多条附件ID
*/
private String[] attrIds;
}
2.文件工具类
import org.apache.commons.lang3.StringUtils;
/**
* <p>
* File工具类,扩展 huTool 工具包
* </p>
*
* @author KanShufan
* @since 2021-07-24 16:37
*/
public class Test extends cn.hutool.core.io.FileUtil{
/**
* 获取文件扩展名,不带 .
*/
public static String getExtensionName(String filename) {
if (StringUtils.isNotEmpty(filename)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length() - 1))) {
return filename.substring(dot + 1);
}
}
return filename;
}
/**
* Java文件操作 获取不带扩展名的文件名
*/
public static String getFileNameNoEx(String filename) {
if (StringUtils.isNotEmpty(filename)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length()))) {
return filename.substring(0, dot);
}
}
return filename;
}
}
3.Controller
/**
* 批量下载
*
* @param response {@link HttpServletResponse}
* @param attachDTO {@link AttachDTO}
* @return ElsResponse<Object>
* @author KanShufan
* @since 2021-07-12 14:21
*/
@RequestMapping("/saveMultipleFun")
public void saveMultipleFun(HttpServletResponse response, @RequestBody AttachDTO attachDTO) {
String[] attrIds = attachDTO.getAttrIds();
if (attrIds == null) {
return;
} else if (attrIds.length == 0) {
return;
}
//获取后台附件数据
List<StdAttachment> attachments = stdAttachmentService.getBaseMapper().selectList(new QueryWrapper<StdAttachment>().in("attr_id", attrIds));
ZipOutputStream zipos = null;
try {
zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
zipos.setMethod(ZipOutputStream.DEFLATED);
} catch (Exception e) {
e.printStackTrace();
}
//循环将文件写入压缩流
DataOutputStream os = null;
InputStream is = null;
for (int i = 0; i < attachments.size(); i++) {
StdAttachment attachment = attachments.get(i);
//获取文件路径
String filePath = attachment.getUrl() + attachment.getFilePath() + attachment.getName();
//获取文件后缀
String suffix = "." + FileUtil.getExtensionName(attachment.getName());
String fileName = FileUtil.getFileNameNoEx(attachment.getName()) + "_" + i + suffix;
try {
//添加ZipEntry,并ZipEntry中写入文件流
zipos.putNextEntry(new ZipEntry(fileName));
os = new DataOutputStream(zipos);
//获取本地文件,url不能带有http
File file = new File(filePath);
is = new FileInputStream(file);
//输入流转换为输出流
IOUtils.copy(is, os);
zipos.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
}
//关闭流
try {
is.close();
os.flush();
os.close();
zipos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
评论区