У меня есть служба загрузки Spring, которая предоставляет файл csv в качестве ответа. Как мы называем эту услугу из машинописного текста angular 5. загрузка файла зависит от некоторых входных параметров, поэтому у меня будет пост-вызов, когда пользователь нажимает кнопку экспорта.
ниже - остальной код в контроллере.
@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();
}
}
}
}
Теперь мне нужно вызвать это из пользовательского интерфейса, когда я нажимаю кнопку экспорта, что написано ниже.
Я прочитал заставку и добавил код ниже, но он не работает. любезно помогите мне.
@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');
});
}
}
Примечание. Когда я запускал URL-адрес для отдыха из браузера, файл загружается, но то же самое должно происходить, когда я нажимаю кнопку экспорта.
Я новичок в технологиях пользовательского интерфейса. Спасибо
проверьте это Как спросить
Спасибо, Марио, извините, только что отправьте сообщение за меньшее время, теперь у меня есть обновление, любезно помогите .. спасибо.
Я исправил проблему с приведенным ниже кодом.
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);
}
}
добавлен ниже в классе компонентов вызывающего абонента.
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');
}) ;
}
}
Спасибо всем за ваши ответы !
У вас есть код для нас? Что-нибудь вы уже реализовали? Мы не будем писать для вас код.