VUE实现文件下载;zip文件也可以下载,干货


// vue 中的调用方法
 handleModelUpload() {
      alert('下载zip模板')
      axios({
        method: 'GET',
        url: '/business/api/download',
        // params: {
        //   // eslint-disable-next-line no-undef
        //   reportRuleId: row.reportRuleId
        // },
        responseType: 'blob'
      }).then(response => {
        const blob = new Blob([response.data], { type: 'application/zip' })
        const url = window.URL.createObjectURL(blob)
        window.location.href = url
      }).catch(error => this.$message.error(error) )
    },



如上图中的前端method,/bussiness 带代理我后台的 ip 实际getMapping的路径是/api/download。下面是后台的java api

package com.picchealth.mono.api;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;


@RestController
@RequestMapping("/api")
public class DemoApi {


    @GetMapping("/download")
    public void download(HttpServletResponse response) throws Exception {
        //文件所在目录路径
        String filePath = "D://xxx.zip";

        System.out.println("文件路径:" + filePath);

        //得到该文件
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("Have no such file!");
            return;
        }

        FileInputStream fileInputStream = new FileInputStream(file);
        //设置Http响应头告诉浏览器下载这个附件,下载的文件名也是在这里设置的
        response.setHeader("Content-Disposition", "attachment;Filename=" +
                URLEncoder.encode("xxx.zip", "UTF-8"));
        OutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[2048];
        int len = 0;
        while ((len = fileInputStream.read(bytes)) > 0) {
            outputStream.write(bytes, 0, len);
        }
        fileInputStream.close();
        outputStream.close();

    }


}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值