java实现文件下载功能

在工作中经常会遇到为文件下载的功能,但因为公司的各种下载时的要求不同,所以都在下载功能上或多或少的加减一些。 今天就总结一下我写过的下载功能MVC的思想 controller层:

/**
     * @Description:下载
     * @Param downloadPath 文件路径
     */
    @GetMapping("/download/downloadZip")
    @ResponseBody
    public void downloadZip(@Param("downloadPath") String downloadPath, HttpServletRequest request, HttpServletResponse response) {
          
   
        //下载图片
        String down = fileUploadService.downloadPathFile(downloadPath, request, response);
    }

Service层–接口:

/**
     * @Description:下载
     * @Param downloadPath 文件路径
     */
    String downloadPathFile(String downloadPath, HttpServletRequest request, HttpServletResponse response);

Service层–实现类

/**
     * @Description:下载
     * @Param downloadPath 文件路径
     */
    @Override
    public String downloadPathFile(String path, HttpServletRequest request, HttpServletResponse response) {
          
   
        //设置文件路径
        File file = new File(path);
        //获取文件名称
        String fileName = file.getName();
        //判断文件是否存在
        if (file.exists()) {
          
   
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
          
   
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
          
   
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                file.delete();
                return "下载成功";
            } catch (Exception e) {
          
   
                e.printStackTrace();
            } finally {
          
   
                if (bis != null) {
          
   
                    try {
          
   
                        bis.close();
                    } catch (IOException e) {
          
   
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
          
   
                    try {
          
   
                        fis.close();
                    } catch (IOException e) {
          
   
                        e.printStackTrace();
                    }
                }
            }
        }
        return "下载失败";
    }
经验分享 程序员 微信小程序 职场和发展