0

Tenho um rest em java onde me retorna um byte[] de um arquivo ZIP. Se eu acessar a URL da API pelo navegador, o arquivo é baixado normalmente sem erro.

Porém se eu tentar realizar o download do arquivo através de uma implementação usando new Blob([response.data], {type: "application/zip"}); no front-end, o arquivo é baixado com erro.

Alguém saberia me dizer onde está o problema?

API

@GET
@Path("/ucmFile")
@Produces("application/zip")
public Response buscarUCMFile(@QueryParam("docName") String docName) throws Exception {

    byte[] file = null;
    String fileName = null;

    try {
        NDC.push(" [buscarUCMFile - userAPI: " + userAPI.getUserAPI() + "] ");

        // Busco o arquivo e fileName

    } catch (ValidationException e) {
        logger.error(e.getMessage(), e);
        Util.validationApplicationException(e.getMessage());
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        Util.applicationException(e);
    } finally {
        NDC.pop();
    }

    return Response.ok(file).header("Content-Disposition", "attachment; filename=" + fileName)
            .header("Content-Length", file.length).build();
}

AngularJS

$http.get(config.HOST_API + vm.listService.config.baseURL + "/ucmFile?docName="+docName).then(function(response) {
    if(response.status === 200) {

        var a = window.document.createElement('a');

        var blob = new Blob([response.data], {type: "application/zip"});
        var url = window.URL.createObjectURL(blob);

        // Append attributes
        a.href = url;
        a.download = fileName;

        // Append anchor to body.
        document.body.appendChild(a);
        a.click();

        // Remove anchor from body
        document.body.removeChild(a);
    } else {
        CustomAlertError("Não foi possivel realizar o download do arquivo.");
    }
}, function(response) {
    CustomAlertError("Não foi possivel realizar o download do arquivo.");
});

2 Respostas 2

0
var file = new Blob([response], {type: 'arraybuffer'});
var fileURL = URL.createObjectURL(file);

Dê uma olhada nestas respostas para mais detalhes.

https://stackoverflow.com/questions/30158115/how-to-download-a-zip-file-using-angular

https://stackoverflow.com/questions/21628378/angularjs-display-blob-pdf-in-an-angular-app/21732039#21732039

0

Com a ajuda dos links do @LR10, a unica alteração que precisei realizar para que o download funcionasse foi no momento do $http.get, onde faltou setar qual seria o responseType.

Com o ajuste, ficou assim:

$http.get(config.HOST_API + vm.listService.config.baseURL + "/ucmFile?docName="+docName , { responseType: 'arraybuffer' }).then(function(response)

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .