js使用Blob的方式实现excel表格的下载(流文件下载)
js前端下载工具
- getToken 为了获取token, 不需要的可以去除
- downLoadXlsx中的
data
, 是数据的搜索参数(根据参数搜索出的结果进行导出), 不需要搜索参数的可以去除data
import axios from 'axios'
import { getToken } from '@/utils/auth'
const mimeMap = {
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
zip: 'application/zip'
}
const baseUrl = process.env.VUE_APP_BASE_API
export function downLoadZip(str, filename) {
var url = baseUrl + str
axios({
method: 'get',
url: url,
responseType: 'blob',
headers: { 'Authorization':
'Bearer ' + getToken() }
}).then(res => {
resolveBlob(res, mimeMap.zip)
})
}
export function downLoadXlsx(str, filename, data) {
var url = baseUrl + str;
axios({
method: 'post',
url: url,
responseType: 'blob',
headers: { 'Authorization': 'Bearer ' + getToken() },
data: data
}).then(res => {
resolveBlob(res, mimeMap.xlsx)
})
}
/**
* 解析blob响应内容并下载
* @param {*} res blob响应内容
* @param {String} mimeType MIME类型
*/
export function resolveBlob(res, mimeType) {
const aLink = document.createElement('a')
var blob = new Blob([res.data], { type: mimeType })
// //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
var contentDisposition = decodeURI(res.headers['content-disposition'])
var result = patt.exec(contentDisposition)
var fileName = result[1]
fileName = fileName.replace(/\"/g, '')
aLink.href = URL.createObjectURL(blob)
aLink.setAttribute('download', fileName) // 设置下载文件名称
document.body.appendChild(aLink)
aLink.click()
document.body.appendChild(aLink)
}
工具的使用:
1.前端代码:
function downLoad(){
// /staffInfo/export为后端接口
// fileName.xlsx" 为文件名称
// this.exportParams /// 数据搜索参数
downLoadXlsx("/student/export", "fileName.xlsx", this.exportParams)
}
2.后端代码:
@RestController
@RequestMapping("/student")
public class student{
@PostMapping("/export")
public void export(@Map<String, Object> params, HttpServletRequest request, HttpServletResponse response){
BufferedOutputStream os = null;
ServletOutputStream outputStream = null;
try {
// 1.设置响应头
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition","attachment;fileName=" + setFileDownloadHeader(request, "fileName.xlsx"));
outputStream = response.getOutputStream();
// 2.从response获取输出流,将excel write到输出流程中
os = new BufferedOutputStream(outputStream);
// 3.根据params参数, 搜索想要导出的数据
// TODO. 获取list
List<Student> students = .....;
// 4.将数据放入,workbooke, 再调用workbooke.write(os), 可以看往期文章
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(os != null) {
os.flush();
os.close();
}
if(outputStream != null){
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}