路径匹配的资源模式解析器

路径匹配-资源解析器


    /**
     * 下载文件
     * @param filePath resource包下的称为classpath路径 /template/partyMemberInfo.xlsx
     * @param fileNewName 给浏览器的名称
     * @param response servlet响应流
     * @throws IOException
     */
    public static void downloadFile(String filePath, String fileNewName, HttpServletResponse response) throws IOException {

		PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        Resource resource = resourcePatternResolver.getResource("classpath:"+filePath); // "/template/partyMemberInfo.xlsx"

        // 临时路径
        String fileTempPath = UtilFile.getTempDirectoryPath() + filePath;

        // 复制到临时路径下 注:jar包中的文件无法直接通过file访问
        FileCopyUtils.copy(resource.getInputStream(), new FileOutputStream(new File(fileTempPath)));

下载文件

fileName是显示给浏览器的
filePath是准备下载的路径(通过上面的路径匹配-资源解析器)

//        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//        response.setHeader("Pragma", "no-cache");
//        response.setHeader("Cache-Control", "no-cache");
        // 配置下载
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        // 下载正常显示中文  fixme 此处的fileName是显示给浏览器的
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(fileNewName.getBytes("UTF-8"), "iso8859-1"));

        // 实现文件下载 fixme filePath代表的:路径+文件名      文件->输入流-缓存-> 输出流
        // try-with-resource 必须是实现AutoCloseable的接口
        try (FileInputStream fis = new FileInputStream(fileTempPath);
             BufferedInputStream bis = new BufferedInputStream(fis);) {

            byte[] buffer = new byte[1024];

            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 error: " + e.getMessage());
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值