Download Zip Files via blob array

Asked

Viewed 897 times

0

I have a rest in java where I return a byte[] of a ZIP file. If I access the URL of the API by the browser, the file is downloaded normally without error.

But if I try to download the file through an implementation using new Blob([response.data], {type: "application/zip"}); in front-end, the file is downloaded with error.

Would anyone know where the problem is?

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 answers

0


With the help of @LR10 links, the only change I needed to make to make the download work was at the time of $http.get, where it failed to set what would be the responseType.

With the adjustment, it went like this:

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

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.