其他分享
首页 > 其他分享> > 2021-05-03

2021-05-03

作者:互联网

SSM文件下载

  1. 获取下载文件位置所有信息
 @GetMapping("/downLoadFiles")
    public  String downLoadFiles(HttpServletRequest request, Model model){
//        读取保存文件的地址,获取名称
        String realPath = request.getServletContext().getRealPath("/upload");
        File savefile=new File(realPath);
        List<String> fileNames = new ArrayList<>();
        File[] files = savefile.listFiles();
        for (File file:files) {
            fileNames.add(file.getName());
        }
        model.addAttribute("fileNames",fileNames);
        return "downLoad";

    }
  1. 获取名字点击下载
   @GetMapping("/fileDownLoad")
    public ResponseEntity downLoad(@PathVariable("fileName") String fileName,HttpServletRequest request) throws IOException {
        String realPath = request.getServletContext().getRealPath("/upload");
        HttpHeaders headers = new HttpHeaders();
//        以流的形式下载
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//        用户手动下载而不是自动下载
        headers.setContentDispositionFormData("attachment",fileName);
       return new ResponseEntity<>(
               FileUtils.readFileToByteArray(new File(realPath,fileName))//把要下载的文件以ByteArray形式返回
               ,headers,//我们自定义响应头信息
               HttpStatus.OK);//状态码


    }

标签:03,String,05,realPath,fileName,2021,File,new,下载
来源: https://blog.csdn.net/weixin_44231005/article/details/116379258