【问题标题】:Download file in angular from java backend service从java后端服务以角度下载文件
【发布时间】: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


    【解决方案1】:

    Angular 尝试将您的 http 响应正文解析为 JSON(这是默认响应类型)。 responseType 没有在 HttpHeaders 中指定,而是在 httpOptions 对象中指定。

    在传递给httpClient.get 的httpOptions 中指定responseType: 'blob'。

    telechargerPieceJointe(id: string): Observable<any> {
        const url = environment.rest.local.recupererDocument + '/' + id;
        const headers = new HttpHeaders({
            Accept: 'application/pdf'
        });
    
        return this.httpClient.get(url, { headers, responseType: 'blob' });
    }
    

    【讨论】:

    • 它有效!我明白问题出在哪里,但不知道如何让它发挥作用。谢谢!
    猜你喜欢
    • 2019-12-15
    • 2015-10-16
    • 2016-03-29
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多