VUE + JAVAは、ダウンロード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) )
    },



上の図に示すように、フロントエンドメソッドである/ bussiness with proxy my back-end ip、実際のgetMappingパスは/ api / downloadです。以下は背景のjavaapiです

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

    }


}

 

おすすめ

転載: blog.csdn.net/AntdonYu/article/details/106855450