java实现文件的下载(前后端代码)

后端部分

  @GetMapping("/t1")
    public void down1(HttpServletResponse response) throws Exception {
        response.reset();
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader(
                "Content-disposition",
                "attachment; filename=Xftp-7.0.0144p.exe");
        try(
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\Xftp-7.0.0144p.exe"));
                // 输出流
                BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        ){
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = bis.read(buff)) > 0) {
                bos.write(buff, 0, len);
            }
        }
    }

前端部分 一个简单的点击事件

<el-button size="mini" @click="download">文件下载</el-button>

  download(){

      location.href="http://localhost:8202/admin/cmn/dict/t1"

    },

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 后端代码: ```java @GetMapping("/download") public void downloadFile(HttpServletResponse response) throws IOException { // 定义文件路径和文件名 String filePath = "/path/to/file.txt"; String fileName = "file.txt"; // 读取要下载文件 File file = new File(filePath); InputStream inputStream = new FileInputStream(file); // 设置响应头 response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8")); // 将文件写入响应输出流 OutputStream outputStream = response.getOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, len); } // 关闭资源 outputStream.close(); inputStream.close(); } ``` 其中,`@GetMapping("/download")` 表示该接口处理 GET 请求,并且路径为 `/download`。`response.setContentType("application/x-download")` 表示返回的数据是二进制数据,并且指定下载文件类型。`response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"))` 表示告知浏览器下载文件,并且指定文件名为 `fileName`。 前端代码: ```html <a href="/download" download>下载文件</a> ``` 其中,`href` 属性指定要下载文件地址,`download` 属性指示浏览器下载文件而不是打开文件。 需要注意的是,要将 Java 后端代码放在一个 Spring Boot 项目中,并且在启动类上添加 `@EnableWebMvc` 注解,以启用 Spring MVC 框架。另外,此代码并没有进行异常处理和文件类型判断,实际开发中需要根据具体需求进行调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值