java下载excel时怎么设置文件投的文件名
使用java导出excel时,需要在response的header中进行设置才能改变浏览器下载文件的文件名,下面介绍具体做法。
代码解释
1、先放出代码,这段代码使用了spring框架,写了一稍僚敉视个download接口,访问它可以导出一个文件。由于文件名与文件格式没有关系,因此suipackage web.controller稆糨孝汶;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import java.io.IOException;import java.net.URLEncoder;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;@Controllerpublic class HomeController { @RequestMapping(value = "download", method = RequestMethod.GET) public void download(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException { Path path = Paths.get("D:\\搜狗高速下载\\apache-jmeter-3.2.zip"); byte[] bytes = Files.readAllBytes(path); String fileName = "文件名wenjianming"; if (request.getHeader("user-agent").toLowerCase().indexOf("firefox") > -1) { //火狐浏览器自己会对URL进行一次URL转码所以区别处理 response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1")); } else { response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"utf-8")); } response.getOutputStream().write(bytes); }}
2、其中用于测试的文件名简单命名为“文件名wenjianming.csv”,包含英文和中文以测试在各浏览器能否正常显示
3、不能直接在header中设置中文,普通浏览器要使用URLEncoder.encode方法encode一下,其中火狐浏览器要区别处理,要转成ISO-8859-1编码。
测试
1、在浏览器上输入本地tomcat的该接口地址如http://localhost:8080/spring4/download谷歌浏览器直接开始下载,文件名识别正确
2、火狐浏览器也能正确识别
3、eage浏览器表现如下
4、再测试一个国产浏览器,也能正常显示。其它国产浏览器基本上也都是chrome内核,不必再测试了。