SpringMVC 实现文件下载

转自:(忘了)

作为程序员,可能会在不经意间就写出来了一段让自己感到骄傲、欣喜、自豪的垃圾代码。对!就是垃圾代码,此处不需要引号!这种情况是可悲的,更可悲的是你自己一直无法发现自己的垃圾之处!我们如果想成长,想在编程的路上走下去,第一个资本就是要:学会、习惯、坚持写优雅的高效的健壮的代码。这个过程不是一触而就的,只能在日常的小事中,自己编写的一段段小的代码中慢慢改进。

原本的写法
/** 
  * @Description 下载文件 
  * @author zhangyd 
  * @date 2015年12月7日 上午10:34:23 
  * @param response 
  * @param file 
  */ 
public static void downLoadFile(HttpServletResponse response, File file) { 
    if (file == null || !file.exists()) { 
        return; 
    } 
    OutputStream out = null; 
    try { 
        response.reset(); 
        response.setContentType("application/octet-stream; charset=utf-8");      
        response.setHeader("Content-Disposition", "attachment; filename=" + file.getName()); 
        out = response.getOutputStream(); 
        out.write(FileUtils.readFileToByteArray(file)); 
        out.flush(); 
    } catch (IOException e) { 
        e.printStackTrace(); 
    } finally { 
        if (out != null) { 
            try { 
                out.close(); 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
        } 
    } 
}
简化的写法
/**
  * @Description 下载文件
  * @author zhangyd
  * @date 2015年12月11日 下午6:11:33
  * @param fileName
  * @param file
  * @return
  * @throws IOException
  */ 
public ResponseEntity download(String fileName, File file) throws IOException { 
    String dfileName = new String(fileName.getBytes("gb2312"), "iso8859-1");  
    HttpHeaders headers = new HttpHeaders(); 
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); 
    headers.setContentDispositionFormData("attachment", dfileName); 
    return new ResponseEntity(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED); 
}

application文件添加配置,这个是配置response的字符编码的,如果不配置,可能会出现乱码等一系列问题

 
 
     
         
             
             
         
     
 
 
     
         
            text/plain;charset=UTF-8 
         
     

你可能感兴趣的:(SpringMVC 实现文件下载)