在客户端Vue应用程序上下载CSV文件的正确方法

时间:2018-10-09 04:13:53

标签: download axios filesaver.js

我有一个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);
}

当我直接在浏览器(chrome)中调用此终结点(即localhost:8080/downloadCsv)时,就会下载csv。

但是,当我点击Vue应用程序中的该端点时,即:

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

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

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

0 个答案:

没有答案