Java实现文件下载

一、前台通过a标签打开接口,传入文件id

<a href="/cdc/announcement/downloadFile/1">下载</a>

二、后台接收id,查找对应文件,进行下载

    @RequestMapping(value = "downloadFile/{id}", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('view')")
    @ResponseBody
    public void downloadFile(HttpServletRequest req, HttpServletResponse resp, @PathVariable("id") Long id) {
        AnnouncementAnnex announcementAnnex = announcementAnnexService.selectById(id);
        //真实文件名
        String name = announcementAnnex.getAnnexUrl();
        String downloadName=announcementAnnex.getAnnexName();
//        进行转码后的文件名,用来下载之后的文件名
        PublicController.download(resp,name,downloadName);
    }

其中download方法

 /**
     * @param resp
     * @param name         文件真实名字
     * @param downloadName 文件下载时名字
     */
    public static void download(HttpServletResponse resp, String name, String downloadName) {
        String fileName = null;
        try {
            fileName = new String(downloadName.getBytes("GBK"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ///home/tomcat/apache-tomcat-9.0.1/files
        String realPath = "D:" + File.separator + "apache-tomcat-8.5.15" + File.separator + "files";
//        String realPath=File.separator+"home"+File.separator+"tomcat"+File.separator+"apache-tomcat-9.0.1"+File.separator+"files";
        String path = realPath + File.separator + name;
        File file = new File(path);
        resp.reset();
        resp.setContentType("application/octet-stream");
        resp.setCharacterEncoding("utf-8");
        resp.setContentLength((int) file.length());
        resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = resp.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
fileName是文件下载之后的名字,filePath是文件所在文件夹地址,path是文件地址,注意设置的响应类型和编码方式

其中File.separator为路径分隔符,他能自动识别是哪个操作系统而使用不同的路径分隔符(windows是‘\’,linux是‘/’)。

  • 3
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值