vue axios+springboot 文件下载

本文详细介绍了使用Java实现文件下载的完整流程,包括后端代码的编写与前端文件的接收。后端通过@RequestMapping注解处理GET请求,利用FileUtils工具类进行文件创建与响应处理,前端则使用axios进行数据请求,最终实现文件的下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下是一个比较完整的流程

后端代码如下:

controller:

@RequestMapping(value = "/download", method = RequestMethod.GET)
public String downloadData(HttpServletResponse res) {
    String data="这是一个下载文件";   //传入数据
    File file=new File("文件.txt");
    FileUtils.getFile(data.getBytes(),file.getName());
    FileUtils.responseTo(file,res);
    file.delete();
    System.out.println("success");
    return "success";
}
复制代码

工具类如下:

public class FileUtils {

public static void getFile(byte[] bfile, String fileName) {    //创建文件
    File file=new File(fileName);
    try {
        if (!file.exists()){file.createNewFile();}
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(bfile);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void responseTo(File file, HttpServletResponse res) {  //将文件发送到前端
    res.setHeader("content-type", "application/octet-stream");
    res.setContentType("application/octet-stream");
    res.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
    byte[] buff = new byte[1024];
    BufferedInputStream bis = null;
    OutputStream os = null;
    try {
        os = res.getOutputStream();
        bis = new BufferedInputStream(new FileInputStream(file));
        int i = bis.read(buff);
        while (i != -1) {
            os.write(buff, 0, buff.length);
            os.flush();
            i = bis.read(buff);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    System.out.println("success");
}
}
复制代码

前端文件接收:

axios({
    url: '/gafzpt/capital/download',
    method: 'get',
    params: {
      capitalId: capitalId
    },
    responseType: 'blob'     //接收类型设置,否者返回字符型
  })
    .then(res => {           //定义文件名等相关信息
      const blob = res.data
      const reader = new FileReader()
      reader.readAsDataURL(blob)
      reader.onload = (e) => {
        const a = document.createElement('a')
        a.download = `现金流文件`
        a.href = e.target.result
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
      }
    })
复制代码

转载于:https://juejin.im/post/5b9297a2f265da0ab5035cac

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值