从Angle 5的Spring Boot Rest Services下载文件 [英] Download a file from spring boot rest services from angular 5
问题描述
我有spring boot服务,它提供csv文件作为响应. 我们如何从angular 5打字稿中调用此服务. 文件的下载应该取决于某些输入参数,因此我将在用户单击导出按钮的情况下进行调用.
I have spring boot service which provides csv file as response. How do we call this service from angular 5 typescript. download of a file should happen depends on some input parameters so I will have post call with user clicks the export button.
下面是控制器中的其余代码.
below is the rest code in controller.
@Controller
public class MyController {
@RequestMapping(value = "/downLoadDataQueryCsv", method = RequestMethod.GET)
public ResponseEntity<Object> downLoadDataQueryCsv(Model model) throws IOException {
FileWriter fileWriter = null;
try {
DataQueryRequestParams dataQueryRequestParams = new DataQueryRequestParams();
dataQueryRequestParams.setMbuCategory("UKY");
// Result table.
List<OrderIdFinalRank> rankList = // call api to get data.
// construct headers
List<String> csvHeaders = constructDataQueryHeaders();
StringBuilder fileContent = new StringBuilder(String.join(",", csvHeaders));
fileContent.append("\n");
// construct file content from response
for(OrderIdFinalRank finalRank : rankList) {
fileContent.append(StringUtils.join(constructDataQueryRow(finalRank), ",")).append("\n");
}
String fileName = new String("DataQueryTab.csv");
fileWriter = new FileWriter(fileName);
fileWriter.write(fileContent.toString());
fileWriter.flush();
File file = new File(fileName);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
ResponseEntity<Object> responseEntity = ResponseEntity.ok().headers(headers).contentLength(file.length())
.contentType(MediaType.parseMediaType("application/txt")).body(resource);
return responseEntity;
} catch (Exception e) {
System.out.println("Exception: " +e);
return new ResponseEntity<>("Error occurred", HttpStatus.INTERNAL_SERVER_ERROR);
} finally {
if(null != fileWriter) {
fileWriter.close();
}
}
}
}
现在,当我单击导出"按钮时,需要从UI调用它,下面是写的内容.
Now I need to call this from UI when I click export button, what have written is below.
我已经阅读了文件保护程序并添加了以下代码,但是它不起作用.请帮助我.
I have read file saver and added below code, but its not working. kindly help me.
@Injectable()
export class ApiService {
onExport(dataQueryRequestParams: any) {
const dataQueryURL = API_URL + '/downLoadDataQueryCsv';
const body = JSON.stringify(dataQueryRequestParams);
this._http.get(dataQueryURL).subscribe(res => {
saveAs(res, 'data.csv');
});
}
}
注意:当我从浏览器运行rest URL时,文件已下载,但是单击导出"按钮时也需要进行同样的操作.
Note: When I ran rest URL from browser the file is downloaded, but the same needs to happen when I click export button.
UI技术的新手. 谢谢
Am new to UI technologies. Thanks
推荐答案
我已解决以下代码的问题.
I have fixed problem with below code.
export class ApiService {
onExport(requestParams: any): Observable<any> {
const dataQueryURL = API_URL + '/downLoadDataQueryCsv';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'Application/json; charset=UTF-8'
}),
responseType: 'text' as 'text'
};
const body = JSON.stringify(requestParams);
return this._http.post(dataQueryURL, body, httpOptions);
}
}
在调用方组件类的下方添加.
added below in caller Component class.
export class Component implements OnInit {
onExport() { this._apiService.onExport(this.dataQueryForm.value).subscribe(data => {
const blob1 = new Blob([data], { type: 'text/csv' });
FileSaver.saveAs(blob1, 'data.csv');
}) ;
}
}
谢谢大家的回应!
这篇关于从Angle 5的Spring Boot Rest Services下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!