首页 > 技术文章 > springboot+vue实现 下载服务端返回的文件功能

yclh 2022-06-22 18:49 原文

     开发中会遇到,通过浏览器下载服务器端返回的文件功能,本文使用springboot+vue实现该功能。

后端代码:

注:后端返回的文件名遇到中文就会乱码,一直也没得到很好的解决方案,最后就统一返回1.xxx的文件,文件名称由前端最终改成实际的文件名(包含中文也没问题)

/**
     * 资源下载。
     *
     * @param filePath 文件路径
     * @return AjaxResult
     */
    @PostMapping("/download")
    @ResponseBody
    public void downloadWord(HttpServletResponse response, HttpServletRequest request,@Valid  String filePath) {

        try {
            //获取文件的路径
            File file = ResourceUtils.getFile(fileSavePath+filePath);

            //文件后缀名
            String suffex = filePath.split("\\.")[1];

            // 读到流中
            InputStream inStream = new FileInputStream(file);//文件的存放路径
            // 设置输出的格式
            response.reset();
            response.setContentType("bin");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("1."+suffex, "UTF-8"));
            // 循环取出流中的数据
            byte[] b = new byte[200];
            int len;

            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

vue

定于网络连接 这里使用到axios通信模块

const instanceImage = axios.create({
    baseURL: config.baseUrl.dev,
    timeout: 60000,
    responseType: 'blob',
    withCredentials: true,
    crossDomain: true,
    // post 使用form-data
    transformRequest: [function(data) {
        data = qs.stringify(data);
        return data;
    }],
    headers: {
        
    }
});

export function postBlob(url, data = {}) {
    return new Promise((resolve, reject) => {
        instanceImage.post(url, data)
            .then((response) => {
                resolve(response);
            })
            .catch((err) => {
                reject(err);
            });
    });
}

export const resourceDownload = (params) => postBlob("download",params);

页面上的调用下载和方法

         
<span style="cursor:pointer;color:#0000FF" @click="downLoadResource()">资源下载</span>



//调用下载的方法


downLoadResource() {
                let paramter = {
                    filePath: '/resource/1.jpg',
                }; resourceDownload(paramter).then(res => { const content = res.data const blob = new Blob([content]) const fileName = '测试.jpg'; const elink = document.createElement('a') elink.download = fileName elink.style.display = 'none' elink.href = URL.createObjectURL(blob) document.body.appendChild(elink) elink.click() URL.revokeObjectURL(elink.href) // 释放URL 对象 document.body.removeChild(elink) }) .catch(error => {}); this.$Message.info('资源下载!'); },

 

推荐阅读