spring-boot 文件下载DEMO 避免中文下载乱码

2017-12-27 - 10,121 Views - 0 Goods - 1 条评论

为了大家方便下载,提供spring boot实战项目,文件下载操作源码分享!

工程目标下载文件路径试图如下:

QQ截图20171227145531

 

前端代码:

 <a href="/person/download">下载人员导入模板文件</a>

后端代码:(利用 spring mvc ResponseEntity 做文件下载,建议使用)

 /**
     * 
     * @Title: download 
     * @Description: 文件下载
     * @author Songliguo
     * @Time:2017年12月27日 下午2:12:02
     * @return
     * @throws IOException
     * @return: ResponseEntity<byte[]>
     */
    @RequestMapping("download")  
    public ResponseEntity<byte[]> download() throws IOException {  
    	String fileName = "人员导入 模板.xlsx";
	String filePath = "personImportTemplate"+ File.separator + fileName;  
	File file = ResourceUtils.getFile("classpath:"+filePath);
	fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");// 为了解决中文名称乱码问题
        HttpHeaders headers = new HttpHeaders();  
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);  
        headers.setContentDispositionFormData("attachment", fileName);  
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);  
    }

后端流操作下载文件:

/**
     * 
     * @Title: templateDownload 
     * @Description: 文件下载
     * @author Songliguo
     * @Time:2017年12月27日 下午2:23:13
     * @param response
     * @param request
     * @throws FileNotFoundException
     * @throws UnsupportedEncodingException
     * @return: void
     */
     @RequestMapping(value = "/templateDownload", method = RequestMethod.GET)
     public void  templateDownload(HttpServletResponse response, HttpServletRequest request) throws FileNotFoundException, UnsupportedEncodingException {
		String fileName = "人员导入 模板.xlsx";
		String filePath = "personImportTemplate"+ File.separator + fileName;  
		File file = ResourceUtils.getFile("classpath:"+filePath);
		fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");// 为了解决中文名称乱码问题
		response.setContentType("application/x-msdownload"); 
		response.setHeader("Content-Disposition", "attachment;filename="" + fileName + """);
		byte[] buff = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(file));
			int i = bis.read(buff);
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				i = bis.read(buff);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		System.out.println("人员导入模板下载成功!");
	}

 

转载请注明原文链接:首页 -> 技术交流 -> 前端开发 -> spring-boot 文件下载DEMO 避免中文下载乱码
  • 支付宝打赏
  • 微信打赏

China.BeiJing

如果说人生是自我编写的程序,那么青春就是其中意味深长的代码