【发布时间】:2019-02-25 16:29:26
【问题描述】:
我正在尝试下载从后端服务器发送的文件。 get 方法在邮递员上运行良好,但我无法通过我的前端应用程序(角度 5)使其工作。
这是我的后端:
@GET
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Path("/recupererDocument/{id}")
@ResponseStatus(value = {Response.Status.OK, Response.Status.BAD_REQUEST,
Response.Status.INTERNAL_SERVER_ERROR,})
@ElementClass(request = Long.class, response = Response.class)
public Response recupererDocument(
@NotNull(message = "L'id (identifiant du document) est obligatoire") @PathParam("id") final String id);
public Response recupererDocument(String id) {
File file = null;
final WebTarget target = ...;
Builder builderDoc = target.request(typeMime);
final Response reponseDocument = builderDoc.accept(typeMime).get();
LOGGER.debug(reponseDocument.getStatus());
if (reponseDocument.getStatus() == 200) {
file = reponseDocument.readEntity(new GenericType<File>() {
});
}
reponseDocument.close();
return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM).build();
}
还有我的前端:
telechargerPieceJointe(id: string): void {
this.s
.telechargerPieceJointe(id)
.then(pj => {
this.downloadFile(pj);
})
.catch(e => {
if (isDevMode()) {
console.log('Erreur : ' + e);
}
});
}
downloadFile(data: Response) {
const blob = new Blob([data], {type: 'application/octet-stream'});
const url = window.URL.createObjectURL(blob);
window.open(url);
}
telechargerPieceJointe(id: string): Promise<any> {
const url = environment.rest.local.recupererDocument + '/' + id;
const headers = new HttpHeaders({
Accept: 'application/pdf',
responseType: 'blob'
});
return this.httpClient.get(url, {headers}).toPromise();
}
现在在我的前端调试中,我没有输入“.then' 方法,而是输入 .catch。
我收到以下消息:
位置 0 处 JSON 中的意外标记 %。
但在 chrome 开发工具的“网络”选项卡中,请求很好(200),我可以在“响应”部分看到我的对象。我不明白为什么它不起作用:/。
如果有人看到我做错了什么,这可能会挽救我的理智。
【问题讨论】:
标签: java angular rest file download