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

    }


}

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页