首页 > 解决方案 > 在客户端 Vue App 下载 CSV 文件的正确方法

问题描述

我有一个 Vue 应用程序,其中有一个“downloadCsv”方法。当按下按钮时,将调用此方法并进行以下 GET 调用:

@GetMapping(value = "downloadCsv")
public ResponseEntity<Resource> exportSubmitted() throws IOException {

    //Generates CSV file and returns fileName
    String filePath = myService.generateCSV();

    InputStreamResource resource = new InputStreamResource(new FileInputStream(filePath));

    return ResponseEntity.ok()
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + "data.csv" + "\"")
        .body(resource);
}

当我直接调用这个端点时,即localhost:8080/downloadCsv在浏览器(chrome)中,csv 被下载。

但是,当我在点击时从我的 Vue 应用程序中调用此端点时,即:

  axios.get(endpoint)
            .then(result => {
        const blob = new Blob([result], {type: 'text/csv'});
        FileSaver.saveAs(blob, 'download.csv');
    });

我无法让浏览器下载文件。

在Vue中调用返回文件并在浏览器中下载文件的rest端点的正确方法是什么?

标签: downloadaxiosfilesaver.js

解决方案


推荐阅读