vue+element+spring cloud文件下载(download)功能+element插槽的使用
场景
文件下载功能实现过程比较简单,但是作者在实现的过程中走了很多弯路。话不多说,上代码
vue端代码
vue代码展示
<div style="width: 100%;height:83%;">
<el-table height="100%" width="100%" ref="moviesTable" :data="FileData">
<el-table-column type="index" label="序号" header-align="center" fixed align="center" width="70">
<template slot-scope="scope">
<span>{
{
scope.$index+1}}</span>
</template>
</el-table-column>
<el-table-column
prop="foldername"
label="文件名称"
header-align="center"
align="center"
max-width="280"
>
<template slot-scope="scope">
<el-button
@click.native.prevent="download (scope.row)"
type="text"
size="small"
>
{
{
scope.row.foldername}}
</el-button>
</template>
</el-table-column>
</el-table>
</div>
js代码展示
//通过链接直接访问java端方法
download(row){
location.href = "http://localhost:1234/upload/downloadFile?newname="+row.newname
},
java端代码展示
@Controller
@RequestMapping("/upload")
public class UploadController {
@Autowired
private UploadService uploadService;
//自定义静态属性展示路径,需要从这里访问需要下载的文件
public static String STATIC_PATH = "D:/fj/";
@Description("模板下载")
@RequestMapping("/downloadFile")
public String downloadFile(HttpServletRequest request,
HttpServletResponse response,
@RequestParam(value = "newname", required = false) String newname) {
String fileName = newname;// 设置文件名,根据业务需要替换成要下载的文件名//newname
if (fileName != null) {
//设置文件路径
String realPath = STATIC_PATH ;
File file = new File(realPath, fileName);
if (file.exists()) {
response.setContentType("application/force-download");// 设置强制下载不打开
try {
// 设置文件名,上传文件时在原文件名称前添加了14位当前时间的字符串,故截取十四位以后的文件名(时间转换为字符串格式详见上一篇博文)
response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName.substring(14), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
//实现文件下载
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("success");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return null;
}
}
效果展示
写在最后
作者新接触vue element框架,目前还是面向百度编程开发阶段。
为实现本文的文件上传功能,参考了不少博主的博客,在此向前辈们表示衷心的感谢。
如有侵权内容,请及时联系作者删除
文件上传 看这里
VUE+Element+Spring Cloud实现文件上传功能(upload)+文件删除功能(remove)+配置spring cloud文件上传路径