Spring MVC - 两种文件下载方式

时间:2022-12-17 21:55:20

第一种、比较优雅,实际应用时遇到问题:IE8下载Excel,内容乱码(待解决)

解决方法:1、使用英文文件名。

                     2、硬编码文件名。String fileName = "我是文件名.xls";

     3、偶尔正常,崩溃了。2015.7.3:硬编码方式也不行了,改用了第二种方法正常。

@RequestMapping(value = "/download/{fileName}")
	public ResponseEntity<byte[]> downloadFile(@PathVariable String fileName)
			throws Exception {
		fileName = fileName + ".xls";
		// 1.拼接真实路径
		String realPath = getRequest().getServletContext().getRealPath("/") + "/" + fileName;
		// 2.读取文件
		File file = new File(realPath);
		
		// 4.设置格式
		HttpHeaders headers = new HttpHeaders();
		headers.setContentDispositionFormData("attachment", encodeChineseDownloadFileName(getRequest(), fileName));
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		// 5.返回下载
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
				headers, HttpStatus.OK);
	}
	
	/**
	 * Description: 根据不同浏览器处理中文字符
	 * @param request
	 * @param fileName
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private String encodeChineseDownloadFileName(HttpServletRequest request, String fileName)
			throws UnsupportedEncodingException{
		String resultFileName = "";
		String agent = request.getHeader("User-Agent").toUpperCase();
		if(null == agent){
			resultFileName = fileName;
		}else{
			if(agent.indexOf("FIREFOX") != -1 || agent.indexOf("CHROME") != -1){  //firefox, chrome
				resultFileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
			}else{  //ie7+
				resultFileName =  URLEncoder.encode(fileName, "UTF-8");
				resultFileName = StringUtils.replace(resultFileName, "+", "%20");  //替换空格
			}
		}
		return resultFileName;
	}

第二种、不会出现上面所说的情况

@RequestMapping(value = "/download/{fileName}")
	public void downloadFile(@PathVariable String fileName) throws IOException{
		// 拼接真实路径
		String realPath = getRequest().getServletContext().getRealPath("/")
				+ "/" + fileName + ".xls";
		// 读取文件
		File file = new File(realPath);
		if(file.exists()){
			OutputStream os = new BufferedOutputStream(getResponse().getOutputStream());
			try {
				getResponse().setContentType("application/octet-stream");
				if (getRequest().getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {   //IE浏览器
					fileName = URLEncoder.encode(fileName + ".xls", "UTF-8");  
				} else {  
					fileName = URLDecoder.decode(fileName + ".xls");//其他浏览器
				}
				
				getResponse().setHeader("Content-disposition", "attachment; filename="
						+ new String(fileName.getBytes("utf-8"), "ISO8859-1")); // 指定下载的文件名
				os.write(FileUtils.readFileToByteArray(file));
				os.flush();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if(os != null){
					os.close();
				}
			}
		}
	}