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);
}
}
}
}