栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > Vue.js

02vue+axios+form实现文件下载(附Java实现代码)

Vue.js 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

02vue+axios+form实现文件下载(附Java实现代码)

1.0前端实现思路

用一个from接收后台返回的文件流。form用display为none隐藏;其中form构造action属性,属性值为后台文件下载的参数。同样可以用display为none的input插入form中,input可以携带参数,后台可以用@requestParam接收。
前端具体代码如下:


    
    
    
    document
    
        
    
    
02.java代码实现

后端Java代码实现首先将文件读入到数组buffer中,然后用response获取输出流,输出流将buffer写出即可。

@GetMapping("/download")    public void download(@RequestParam("path") String path, HttpServletResponse response) {
        System.out.println(path);        try {            // path是指欲下载的文件的路径。
            File file = new File(path);            // 取得文件名。
            String filename = file.getName();            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();            // 以流的形式下载文件。
            InputStream fis;
            fis = new BufferedInputStream(new FileInputStream(path));            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();            // 清空response
            response.reset();            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }



作者:exmexm
链接:https://www.jianshu.com/p/a0fb5b1e63b3


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/240666.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号