栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java实现文件下载功能

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java实现文件下载功能

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

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

Service层–接口:

    String downloadPathFile(String downloadPath, HttpServletRequest request, HttpServletResponse response);

Service层–实现类

 
    @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 "下载失败";
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/759774.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号