java - 如何使用角度从java接收文件csv
问题描述
我有一个返回 a 的 rest api,file.csv
然后我检查响应是否为200
,并且数据也在responsed.body
.
但是浏览器没有下载 csv 文件。
这是 API:
ResponseEntity<Resource> exportCsv() throws IOException {
/*
*
*/
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
HttpHeaders headers = new HttpHeaders();
headers.add("Content-disposition", "attachment; filename=sample.csv");
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("text/csv"))
.body(resource);
}
这是角
this.stickService.exportCsv( this.stickSearch ).subscribe(
response => this.downloadFile(response),
err => console.log('Error downloading the file.' + err.message
));
downloadFile(data: Response) {
const blob = new Blob([data], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
window.open(url);
}
exportCsv( stickSearch: StickSearch ): Observable<any> {
const headers = this.oAuthService.putTokenInHeaders(this.headers);
let params = new HttpParams({encoder: new HttpURIEncoder()});
if (stickSearch.searchString() !== '') {
params = params
.append('search', stickSearch.searchString())
}
return this.httpClient.get(this.exportCsvUrl + '/exportCsv',
{
responseType: 'text',
params: params,
headers
});
}
我在响应正文中获得了正确的数据。
但是下载失败。 'Error downloading the file.Http failure during parsing for myURL '
感谢您的帮助
它现在工作,这是结果非常感谢!
解决方案
我可以看到您正在获取服务器提供的输出,然后从该 CSV 构建一个 URL。那将没有必要。如果您只想下载 CSV,那么您所缺少的只是 Java 代码中的以下内容:
headers.add("Content-disposition", "attachment; filename=sample.csv");
一旦有了标头,您就可以摆脱该downloadFile
方法,并可能将this.httpClient.get
请求更改为window.open
.
看看这是否能解决您的问题并在任何一种情况下提供反馈。
推荐阅读
- string - 将工作日字符串解析为 time.Weekday
- javascript - jQuery .find() 返回未定义
- c - 数组接收的 MPI 总和仅适用于一级
- java - java.lang.AssertionError:预期状态:<201> 但原为:<400>
- jquery - Jquery Ajax Typo3 问题 - 加载主页
- javascript - 在 Node.js 中如何从 Php 中检索数据
- batch-file - 使用 start chrome 从 URL 下载文件
- javascript - 在边缘使用 location.reload 不起作用
- go - 当格式字符串来自参数时,fmt.Printf 中出现类似“%!s”的错误(go 语言)
- three.js - 如何获得在three.js中由骨骼缩放的网格的大小?