2021-04-14|2021-04-14 Springboot项目向前端返回UTF-8编码的文件

看部署方式,jvm启动-浏览器直接访问【IP:PORT/sync/service/getdata】;部署在tomcat中【tomcat配置的IP:PORT/项目名/sync/service/getdata】

import javafx.application.Application; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.Date; @Controller @SpringBootApplication @MapperScan("cy.test.unit.dao") public class UnitApplication extends SpringBootServletInitializer {@Value("${CSVFile.location}") private String location; public static void main(String[] args) { SpringApplication.run(UnitApplication.class, args); }@Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(UnitApplication.class); }/** * 文件下载 * * @param request * @param response * @return */ @RequestMapping("/sync/service/getdata") public void downloadFile(HttpServletRequest request, HttpServletResponse response, String name) throws Exception { String FullPath = location + name; //将文件的统一储存路径和文件名拼接得到文件全路径 File packetFile = new File(FullPath); String fileName = packetFile.getName(); File file = new File(FullPath); // 如果文件名存在,则进行下载 if (file.exists()) { // 配置文件下载 response.setHeader("content-type", "application/octet-stream"); response.setContentType("text/plain; charset=UTF-8"); // 下载文件能正常显示中文 response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8")); // 实现文件下载 //指定编码 InputStreamReader reader = new InputStreamReader(new FileInputStream(file)); OutputStream os = response.getOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(os, "UTF-8"); char[] chs = new char[1024]; int len = 0; while ((len = reader.read(chs)) != -1) { writer.write(new String(chs, 0, len)); } reader.close(); writer.flush(); writer.close(); } else {//对应文件不存在 } } }

    推荐阅读