Download Zip Files through blob array

0

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

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

Could anyone tell me 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.");
});
    
asked by anonymous 21.01.2018 / 13:32

2 answers

0

With the help of the @ LR10 links, the only change I had to make to make the download work was at the time of $http.get , where it was missing what responseType .

With the setting, it looks like this:

$http.get(config.HOST_API + vm.listService.config.baseURL + "/ucmFile?docName="+docName , { responseType: 'arraybuffer' }).then(function(response)
    
22.01.2018 / 12:43
0
var file = new Blob([response], {type: 'arraybuffer'});
var fileURL = URL.createObjectURL(file);

Take a look at these answers for more details.

link

    

21.01.2018 / 16:40