Java代码下载功能在 Tomcat7、8 不同环境中,中文乱码问题

前两天给客户的新电脑上部署系统忽然发现一个问题,同样的代码在自己的开发环境(Tomcat7)中下载中文名的文件没有任何问题。但是在客户的电脑环境(Tomcat8)上,却遇到了文件找不到和找到文件后下载包含中文的文件,文件名乱码问题。静下心对比各个可能出问题的环节,猜想问题可能出在 web 服务器上,又忽然想起之前看过的一篇关于 Tomcat7Tomcat8 不同点对比的文章,其中有一个点就是说 Tomcat7 的默认编码为 ISO8859-1Tomcat8 以后则为 UTF-8 。这个思路的出现也让上述的所有问题迎刃而解。

上代码

import java.io.File;
import java.io.FileNotFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ev_image.util.CommonUtil;

@Controller
@RequestMapping("/download")
public class DownloadController {
	private static final Logger logger = Logger.getLogger(DownloadController.class);
	private static final String javaVersion = "8";
	/**
	 * @Title: downloadCommonFile
	 * @Description: Tomcat7 的默认编码为 ISO8859-1 , Tomcat8 以后则为 UTF-8
	 * @param fileName
	 * @param req
	 * @param resp
	 * @return ResponseEntity<byte[]>
	 * @throws null
	 */
	@RequestMapping("/commonFile")
	@Scope("prototype")
	public ResponseEntity<byte[]> downloadCommonFile(@Param("fileName") String fileName, HttpServletRequest req, HttpServletResponse resp) {
		try {
			if (StringUtils.isNoneBlank(fileName)) {
				// 转换文件名称编码格式,否则编码出错后便导致找不到文件
				String file = null;
				if("7".equals(javaVersion)){
					file = new String(fileName.getBytes("ISO-8859-1"), "utf-8");
				}else{
					file = fileName;
				}
				// 获取配置在 web.xml 中的文件路径
				String filePath = CommonUtil.getReportGeneratorPath();
				
				logger.info("正在下载文件:___________"+filePath+file);
				// 设置响应头,确保文件名最终编码格式为 ISO-8859-1 					
				HttpHeaders headers = new HttpHeaders();
				// 根据不同 Tomcat 版本设定编码格式,否则会导致下载的文件名中,中文部分乱码
				if("7".equals(javaVersion)){
					// Tomcat7 默认编码格式为 ISO-8859-1 所以这里不用转码
					headers.setContentDispositionFormData("attachment", fileName);
				}else{
					// Tomcat8 默认编码格式为 UTF-8 所以这里需将文件名转码为 ISO-8859-1 编码
					headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
				}
				// 设置响应内容类型
				headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
				// 判断文件是否存在
				File downloadFile = new File(filePath +  file);
				if(downloadFile.exists()){
					// 返回文件流
					return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(downloadFile), headers, HttpStatus.CREATED);
				}else{
					// 抛出文件未找到异常
					throw new FileNotFoundException();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

猜你喜欢

转载自blog.csdn.net/Supreme_Sir/article/details/92834057