vue前端 + java文件下载

5 篇文章 0 订阅

vue部分前端代码

<el-table-column
    prop="displayName"
	min-width="100"
	show-overflow-tooltip
	header-align="center"
	label="附件名称">
        <template slot-scope="scope">
            <el-link style="color: #409eff;cursor: pointer" @click="downLoadFile(scope.row)">
                {{scope.row.displayName}}
                    </el-link>
        </template>
</el-table-column>
downLoadFile(rowData) {
    // 不用ajax请求,而是用普通的方式 这是重点!
    let basePath = gbs.host + gbs.adminContext + '/knowlgAttach/downloadFile'
    let exportParams = {kaId: rowData.kaId, displayName: rowData.displayName};
    let path = basePath + "?param=" + encodeURI(JSON.stringify(exportParams));
    window.location.href = path;
}

java后端代码

@RestController
@RequestMapping("/knowlgAttach")
public class KnowlgAttachController {
    @RequestMapping("/downloadFile")
    public void downloadFile(HttpServletResponse resp, @RequestParam String param) throws Exception {
        KnowlgAttachDomain item = JSON.parseObject(param,KnowlgAttachDomain.class);
        // 从es中获取文件信息 SFFile的父类是File
        // 大致过程是从es中获取文件加载到本地缓存 SFFile存储文件路径等信息
        // 本质就是加载本地缓存中的文件内容并且通过响应(下载)的方式读取,来达到下载的过程
        SFFile file = imFileService.getFile(item.getKaId());
        String name = item.getDisplayName();
        String[] arr = name.split("\\.");
        String type = arr[1];
        resp.reset();
        // 设置响应方式
        resp.setContentType("application/x-download");
        resp.setCharacterEncoding("utf-8");
        // 下载文件名中文乱码处理
        resp.setHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes("gbk"), "iso8859-1") + "." + type);
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(file);
            output = resp.getOutputStream();
            byte[] b = new byte[4096];
            int i = 0;
            while ((i = input.read(b)) > 0) {
                output.write(b, 0, i);
            }
            output.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            file.delete();
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(output);
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值