为了账号安全,请及时绑定邮箱和手机立即绑定

springboot从服务器下载文件,代码干货

标签:
SpringBoot

    今天给大家分享一个springboot从服务器下载文件的方法,话不多说直接上代码:

    controller层代码

@RequestMapping("/download")

    public Map<String,String> download(HttpServletRequest request,HttpServletResponse response,String fileName) throws UnsupportedEncodingException {

        Map<String,String> map = new HashMap<>();

        String rootPath = System.getProperty("user.dir")+"\\src\\main\\resources\\uploadFile\\";//存储文件的目录

        String FullPath = rootPath + fileName;//文件的位置

        File packetFile = new File(FullPath);

        String fn = packetFile.getName(); //下载的文件名

        System.out.println("filename:"+fn);

        File file = new File(FullPath);

        // 如果文件名存在,则进行下载

        if (file.exists()) {

            // 配置文件下载

            response.setHeader("content-type", "application/octet-stream");

            response.setContentType("application/octet-stream");

            // 下载文件能正常显示中文

            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            // 实现文件下载

            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);

                }

                System.out.println("Download the song successfully!");

            } catch (Exception e) {

                System.out.println("Download the song failed!");

            } finally {

                if (bis != null) {

                    try {

                        bis.close();

                    } catch (IOException e) {

                        e.printStackTrace();

                    }

                }

                if (fis != null) {

                    try {

                        fis.close();

                    } catch (IOException e) {

                        e.printStackTrace();

                    }

                }

            }

            return null;

        } else {//对应文件不存在

            map.put("result","failed");

            return map;

        }


    }

    前端代码

function  downloadFile(fileName){

    window.open("/meeting/download?fileName="+fileName);

}

   以上便是关于springboot从服务器下载文件的代码,大家学会了吗,如果还有问题可在评论区留言~

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消