文件下载有很多方式 比如a标签 href文件路径,但是有的路径非项目静态路径,所有用文件流方式完成文件下载

前端请求

downLoadReport(e) {
                this.axios({
                    method: 'get',
                    url: '/download',
                    params: {
                        'path': e.reportPath,
                    }
                    // responseType: 'blob'
                }).then(function (response) {
                    console.log(response.data);
                    // let contentDisposition = response.headers['content-disposition'];
                    // 将URL参数数值转成汉字
                    // if (response.data)
                    let fileList = e.reportPath.split('/');
                    let fileName = fileList[fileList.length-1]
                    // 处理IE以及IE内核的浏览器兼容问题
                    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                        navigator.msSaveBlob(response.data, fileName);
                    } else {
                        // 处理google firefox浏览器兼容问题
                        let url = window.URL.createObjectURL(new Blob([response.data]));
                        let a = document.createElement('a');
                        a.style.display = 'none';
                        a.href = url;
                        a.setAttribute('download', fileName);
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        window.URL.revokeObjectURL(url);
                    }
                    }.bind(this)).catch(function (error) {
                    alert(error);
                });
            }

后端代码

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@RequestMapping("/download")
    public String downloadFile(HttpServletRequest request,
                               HttpServletResponse response) throws Exception {
        String path=request.getParameter("path");
        //设置文件路径
        File file = new File(path);
        // 如果文件名存在,则进行下载
        if (file.exists()) {
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(path, "UTF-8"));
            // 实现文件下载
            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);
                }
            } catch (Exception e) {
                System.out.println("Download the song failed!");
            } 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;
    }
Last modification:August 25th, 2020 at 01:55 pm
如果觉得我的文章对你有用,请随意赞赏