1.前端定义下载按钮
<template>
<div>
<el-button @click="downLoad" id="down">下载MD</el-button>
</div>
</template>
定义下载方法download()
//下载MD文件
async downLoad(){
var id=1;
//通过axios.defaults.baseURL获取baseURL,此处传递文件的id,注意导入axios!!
window.location.href=axios.defaults.baseURL+"downloadFile/"+id;
},
注意,这里不能用axios传递参数到后端,因为axios主要运用ajax技术,ajax方式请求的数据只能存放在javascipt内存空间,可以通过javascript访问,但是无法保存到硬盘,因为javascript不能直接和硬盘交互,否则将是一个安全问题。
2. axios中baseURL定义
//定义axios访问地址
axios.defaults.baseURL = 'http://localhost:8080/api/'
3. 后端controller层处理
//下载Md文件
@GetMapping("/api/downloadFile/{id}")
public void downloadFile(@PathVariable("id") long id, HttpServletRequest request, HttpServletResponse response) {
//1.获取文件绝对路径
Article ar = articleService.queryById(id);
String path = ar.getPath();
//2.通过绝对路径定义File
File f=new File(path);
//3.调用FileUtil下载文件
FileUtil.downloadFile(request,response,f,false);
}
其中articleService对应文章存储表的处理接口
articleService.queryById(long id),通过id获取表对象,关于springboot与存储表如何建立联系,如何创建接口见“springboot 利用mybatis操作mysql数据库-常规流程”
3. 对应FileUtil中的downloadFile()函数
此处downloadFile()复用eladmin中FileUtil中该函数
/**
* 下载文件
*
* @param request /
* @param response /
* @param file /
*/
public static void downloadFile(HttpServletRequest request, HttpServletResponse response, File file, boolean deleteOnExit) {
response.setCharacterEncoding(request.getCharacterEncoding());
response.setContentType("application/octet-stream");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
//response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
IOUtils.copy(fis, response.getOutputStream());
response.flushBuffer();
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (fis != null) {
try {
fis.close();
if (deleteOnExit) {
//file.deleteOnExit();
file.delete();
System.out.println("已删除");
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}
4. 检测
点击"下载md"按钮,浏览器将表中"F:/note/555.md"对应文件直接下载到本地。