快捷搜索: 王者荣耀 脱发

使用 responseentity进行文件的下载

文件的下载的功能是系统必不可少的功能,自己手写有些麻烦,这时候springMVC为我们提供一种简单的方式使用 responseentity 进行文件下载,具体代码如下:

// 根据文件id 进行文件的下载
 @RequestMapping("/downloadFile/{id}")
    public ResponseEntity<InputStreamResource> downFile(@PathVariable("id") String id) throws Exception{
          
   
   		// 根据文件 id 从数据库中查询出文件的一些基本信息
        SysFileImportEntity sysFileImportEntity=sysFileImportService.selectById(id);
        if(sysFileImportEntity!=null){
          
   
        	// 文件的原始名称
            String fileName=sysFileImportEntity.getOrginFileName();
            // 文件在服务器上存放的路径
            String filePath=sysFileImportEntity.getFilePath();
            File file = new File(filePath);
            InputStream inputStream = new FileInputStream(file);
            InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
            HttpHeaders headers = new HttpHeaders();
            if(sysFileImportEntity.getTemplateName().equals("solutionAudioUploadList")){
          
   
                headers.add("Accept-Ranges", "bytes");
            }
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", String.format("attachment; filename="%s"", URLEncoder.encode(fileName,"UTF-8")));
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            return ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentLength(file.length())
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(inputStreamResource);
        }else {
          
   
            InputStream inputStream = new ByteArrayInputStream("<script language="javascript">alert(文件不存在!);</script>".getBytes("GBK"));
            InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_TYPE,"text/html;charset=UTF-8");
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            return ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentType(MediaType.TEXT_HTML)
                    .body(inputStreamResource);
        }
    }
经验分享 程序员 微信小程序 职场和发展