Springboot导出文件,前端下载文件

本文介绍了一个后端文件下载的实现方法,使用Java的SpringMVC框架通过POST请求提供文件下载服务,并详细展示了如何在前端利用Axios进行文件流的接收和处理,包括设置响应类型、字符编码及文件名的编码处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

后端代码:

可以把请求设置为post,我这里是Get

  @RequestMapping(value = "/download", method = RequestMethod.POST)
    public void download(HttpServletRequest request, HttpServletResponse res) throws Exception {
        File excelFile = new File("/Users/i501695/GitHUbProject/EN_ProductIntergration/databaseclient/src/main/resources/Files/ProductTemplateCopy.xlsx");
        res.setCharacterEncoding("UTF-8");
        String realFileName = excelFile.getName();
        res.setHeader("content-type", "application/octet-stream;charset=UTF-8");
        res.setContentType("application/octet-stream;charset=UTF-8");
        //加上设置大小下载下来的.xlsx文件打开时才不会报“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃”
        res.addHeader("Content-Length", String.valueOf(excelFile.length()));
        try {
            res.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(realFileName.trim(), "UTF-8"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(excelFile));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

前端伪代码结合Axios(核心代码一样,只是结合了Axios)

   Axios({ // 用axios发送post请求
                method: 'post',
                url: 'http://127.0.0.1:8762/dataService/download', // 请求地址
                data: formData, // 参数
                responseType: 'blob' // 表明返回服务器返回的数据类型
            })
                .then((res) => { // 处理返回的文件流
                    let blob = new Blob([res.data], {type: res.data.type})
                    const fileName = 'ProductTemplateCopy.xlsx';
                    let downloadElement = document.createElement('a')
                    let href = window.URL.createObjectURL(blob); //创建下载的链接
                    downloadElement.href = href;
                    downloadElement.download = fileName; //下载后文件名
                    document.body.appendChild(downloadElement);
                    downloadElement.click(); //点击下载
                    document.body.removeChild(downloadElement); //下载完成移除元素
                    window.URL.revokeObjectURL(href); //释放blob
                    message.success('upload successfully.');
            })
            .catch(function (error) {
                console.log(error);
            });

 

### 关于SpringBoot项目中导出Excel功能的前端实现 在SpringBoot项目中,要实现出Excel的功能,通常需要前后端配合完成。以下是前端部分的一个简单示例代码: #### HTML部分 HTML页面用于触发下载操作,可以通过按钮点击事件来发起请求。 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Export Excel</title> </head> <body> <button id="exportBtn">导出Excel</button> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#exportBtn').on('click', function () { exportExcel(); }); }); function exportExcel() { $.ajax({ url: '/api/export/excel', method: 'GET', xhrFields: { responseType: 'blob' // 设置响应类型为Blob对象 }, success: function (data) { const blob = new Blob([data], {type: 'application/vnd.ms-excel'}); const link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = 'example.xlsx'; // 文件名 link.click(); }, error: function (error) { console.error('导出失败:', error); } }); } </script> </body> </html> ``` 上述代码展示了如何通过AJAX请求获取后端返回的文件流,将其保存为Excel文件[^1]。 #### JavaScript说明 - 使用`$.ajax()`发送HTTP GET请求到指定API路径。 - `xhrFields.responseType='blob'`设置响应的数据类型为二进制大对象(Blob),以便处理文件流。 - 创建一个临时链接(`<a>`标签),通过`window.URL.createObjectURL()`生成指向该Blob对象的URL地址。 - 调用`link.click()`模拟用户点击行为从而触发浏览器自动下载文件[^2]。 此方案适用于大多数现代Web应用程序中的文件下载需求,能够很好地满足将服务器上的资源作为附件供客户端访问的要求[^3]。 ### 注意事项 如果涉及大量数据,则需考虑性能优化问题以及内存占用情况;对于复杂场景可以采用分页加载或者异步传输等方式减少单次交互的压力[^4]。外,在实际部署过程中还需要注意跨域资源共享(CORS)策略配置等问题以保障安全性[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值