最近做需求时遇到一个可向导的文件上传功能,现在做完了来分享下,基本能满足大伙80%的需求了
一、Excel 模板下载功能
后端代码(这是07版的Excel,需要03版的修改 XSSFWorkbook workbook = new XSSFWorkbook(fis);
这行代码即可):
public void download(HttpServletResponse response) throws IOException {
FileInputStream fis = new FileInputStream("文件路径");
ServletOutputStream out = null;
try {
XSSFWorkbook workbook = new XSSFWorkbook(fis);
response.setContentType("application/binary;charset=ISO8859-1");
String fileName = java.net.URLEncoder.encode("模板文件名字", "UTF-8");
response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");
out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭文件输出流
fis.close();
}
return;
}
前端代码:
main.js:
引入跨域请求依赖axios
import axios from 'axios'
挂载axios
Vue.prototype.$http = axios
设置访问根路径
axios.defaults.baseURL = "http://localhost:端口号看后端"
JS代码:
downloadFile() {
this.$http({
method: "get",
headers: {
"content-type": "application/json", // 默认值
Authorization: "Bearer " + sessionStorage.getItem("access_token"),
},
url: '后端接口地址',
params: {
'name':'Jack'},
responseType: "blob",
}).then(function (res) {
let blob = new Blob([res.data]); // { type: "application/vnd.ms-excel" }
let url = window.URL.createObjectURL(blob); // 创建一个临时的url指向blob对象
// 创建url之后可以模拟对此文件对象的一系列操作,例如:预览、下载
let a = document.createElement("a");
a.href = url;
a.download = "上传模板.xlsx";