spring mvc 文件下载&&解决文件名乱码问题

 @RequestMapping("/download")
    public ResponseEntity<byte[]> export(@RequestParam("id") Long id, HttpServletRequest request) throws IOException {
        TKnownledgeFile knownledgeFile = knownledgeFileMapper.selectTKnownledgeFileById(id);
     //得到原始文件名称 String fileName
= knownledgeFile.getFileName(); HttpHeaders headers = new HttpHeaders();
     拿到存在你服务器上的文件,路径必须是绝对路径 File file
= new File(FileUploadUtils.getDefaultBaseDir() + knownledgeFile.getFilePath()); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
     //判断浏览器类型,火狐的浏览器编码为 iso-8859-1 所以要单独处理
if(request.getHeader("USER-AGENT").toLowerCase().contains("firefox")){ fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1"); headers.setContentDispositionFormData("attachment", fileName); }else{
       //其他浏览器类型可以用一下代码方式解决中文文件名乱码问题 headers.setContentDispositionFormData(
"attachment", URLEncoder.encode(fileName, "UTF-8")); } return new ResponseEntity<byte[]>(org.apache.commons.io.FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED); }

 

posted @ 2019-11-13 13:03  刘阿泽  阅读(1544)  评论(0编辑  收藏  举报