【Java】接口返回【下载文件】【文件名】【中文乱码】问题解决

Background

最近有个项目有数据导出的功能,文件格式为xls,文件名是中文,结果下载时返回的文件名乱码,最终解决方案如下。

1、接口代码

	@PassToken
    @ApiOperation("导出报表")
    @ApiImplicitParam(
            name = "typeId",
            value = "1单用户日报表,2单用户月报表,3全用户日报表,4全用户月报表",
            required = true
    )
    @GetMapping("/exportToExcel")
    public void exportToExcel(@RequestParam(value = "typeId") Integer typeId, HttpServletResponse response) {
        try {
            String filePath = "data/export/data-20210722165833/明邦建材蒸汽历史数据.xls";
            ResponseUtil.downloadFile(filePath, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2、工具类 ResponseUtil

package com.cloudansys.hawkeye.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.io.FileUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

public class ResponseUtil {

   /**
     * 提供文件下载
     *
     * @param filePath 要下载的文件路径
     * @param response 下载请求响应对象
     */
    public static void downloadFile(String filePath, HttpServletResponse response) {
        File file = new File(filePath);
        if (file.exists()) {
            String fileName = new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            OutputStream os = null;
            try {
                os = response.getOutputStream();
                response.reset();
                response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
                response.setHeader("Access-Control-Allow-Headers", "Content-Type");
                response.setContentType("application/octet-stream; charset=utf-8");
                os.write(FileUtils.readFileToByteArray(file));
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(os);
            }
        }
    }

}

在这里插入图片描述

3、第二种方法(推荐)

使用Hutool工具类ServletUtil

  • 引入依赖
		<dependency>
			<groupId>cn.hutool</groupId>
			<artifactId>hutool-extra</artifactId>
			<version>5.8.23</version>
		</dependency>
		<dependency>
		    <groupId>javax.servlet</groupId>
		    <artifactId>javax.servlet-api</artifactId>
		    <version>3.1.0</version>
		    <!-- 此包一般在Servlet容器中都有提供 -->
		    <scope>provided</scope>
		</dependency>
  • 使用
@PostMapping("/template/pollutant")
    @ApiOperation("污染物监测数据-数据导入模板下载")
    @LogNotes(title = "污染物监测数据", content = "数据导入模板下载")
    public void pollutantImportTemplate(HttpServletResponse response) {
        try {
            String filepath = Const.TPL_EXPORT_POLLUTANT_IMPORT_FILEPATH;
            ExcelUtil.writeAllSheetWithHeader(writeParam);
            response.setCharacterEncoding("UTF-8");
            ServletUtil.write(response, new File(filepath));
            FileUtil.del(new File(filepath));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WaiSaa

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值