vue+jave实现文件报表增加文件下载功能

需求背景:系统有文件交互功能。但没有做页面展示。为了测试方便,写了报表展示并可下载文件做检查。(所以下载是依赖表数据的)

使用语言和框架:
前端:vue-cli 后端:springBoot

前端实现
1、在报表vue文件,显示下载按钮并实现下载接口请求和处理。

//报表操作栏添加下载按招
//  slot-scope="{ row, $index ) -- 绑定行数据
// downloadFile(row, $index)"-- 调下载方法,入参行数据
// v-if="'0, 1, 2, 6+ 7 . indexOf(row.FILE_STATUS)>= 0” -- 指定文件状态才显示下载按钮 
<el-table-colum label="操作”width="120" fixed="right" align="center">
<template slot-scope="{ row, $index }"
<el-button v-if="2,3,5,9 '.indexOf(row. FILE_STATUS) >= 0" type="primary" size="mini" @c1ick="downloadFile(row, $index)>下载</el-button>
<el-button> v-if="'0, 1; 2, 6, 7'. indexOf(row.FILE_STATUS) >= 0" type-"primary" size="mini" @click="openUploadFileDielog(row,$index)">上传</el-button>
</template)
</el-table-column>
// js脚本
<script>
//导入需要用到的api
import { getReportList,downloadFile } from '@/api/report'

// method 增加下载方法
//文件下载
downloadFile(row){ 
const params ={
fileType : encodeURIComponent(row.FILE_TYPE ), 
fileDir : encodeURIComponent(row.FILE_DIR), 
id:row.ID}
downloadFile(params).then(res ->{ 
console.log("下载的文件流”,res)
const link=document.createElement('a'); 
try{
let blob =res.data //如果后台返回的直接是b1ob对象类型,直接获取数据
console.log(JSON.stringify(res.headers ))
let _fileName = res.headers['content-disposition' ].split('; ')[1].split('=')[1];//拆解读取文件名
link.style.display='none';
const url = window.URL || window.webkitURL || window.moxURL;
link.href=window.URL.createObjectURL(new Blob([blob],(type:'application/txt'}));
link.download =_fileName; //下载的文件名称
link.click();
window.URL.revokeObjectURL(ur1);
}catch (e){
console.log('下载的文件出错',e)
}
})
}
</script>

2、接口管理页面,新增下载接口
\项目路径\src\api\report.js

// 下载接口
export function downloadFile(data) {
return request({
url: '/downloadFile', 
method: 'post', 
timeout: 90000,
responseType: 'blob', 
data
})
}

后端实现
1、controller新增接口

@RequestMapping(value ={"/{env}/downloadFile"})
public vaid downloadFile(@PathVariable String env, @valid FileDTO fileDTO,HttpServletRequest httpRequest,HttpServletResponse response) throws IOException {
xxServiceImpl.downloadFi1e(env,response,fileDTO);

xxServiceImpl = service类名

2、service层实现下载功能

public void downloadFile(String env, HttpServletResponse response,FileDTO fileDTO) throws BizException, IOException {
System,out.println("downloadFile fileDTO =" + fileDTO);
// 本来是需要通过fileDTO来获取文件路径的,省略,假设文件路径在./filePath/fileName.XX  
//服务器文件路径,仅当下载服务跟文件在同一个服务器时可行。如果文件在其他服务器,需要开通ssh访问权限后,通过 sshConnect来获取文件。
String localPath ="./filePath/fileName.XX"; 
String os = System.getProperty("os.name").toLowerCase();
// 方便本地调式下载功能
if (os.contains("windows")){
localPath = "D:\localPath\fileName.xx"; 
}
OutputStream out= null; 
InputStream is= null;
try{
File file = new File(localPath);
//包装错误信息
if (!file.exists()){
System.out.println("文件不存在"+ localPath); 
JSONObject res = new JSONObject();
String err = localPath +”文件不存在"; 
res.put("desc",err);
response.setContentType("application/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.getOutputStream().write(res.toString().getBytes("UTF-8")); 
return;
}
String fileName =file.getName();
fileName = new String(fileName.getBytes("UTF-8"),"iso8859-1"); 
System.out.println("fileName="+ fileName);
//防止前端找不到 content-disposition
response.setHeader("Access-Control-Expose-Headers", "content-disposition"); 
response.setHeader("content-disposition","attachment;filename="+ fileName);
response.setContentType("application/x-download"); 
response,setCharacterEncoding("GBK"); 
response.addHeader("Pargam","no-cache");
response,addHeader("Cache-Control", "no-cache"); 
response.flushBuffer();
//获取文件流
is = new FileInputStream(fu11Fi1eNamePath); 
int len =0;
byte[] b = new byte[1024];
out = response.getOutputStream(); 
while ((len = is.read(b)) != -1){
//将缓冲区数据输出到浏览器 
out.write(b,0, len);
}
out.flush( );
} catch (Exception e) {
System.out .println("e.getMessage() = " + e.getMessage());
} finally {
try{
if (null != out) {
out.close();
}
if (null != is) {
is.close();
} catch (Exception e){
System.out.println("e = " + e.getMessage());
}}}

ps: 依赖包都是框架有的,爆红的位置按键alt+enter,按提示导入即可。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值