赞
踩
最近有个项目有数据导出的功能,文件格式为xls,文件名是中文,结果下载时返回的文件名乱码,最终解决方案如下。
@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(); } }
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); } } } }
使用
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();
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。