0
votes

I spent a couple of days on this problem and read hundreds posts. But i still can't resolve it.

REST Controller:

@RequestMapping(value = "/goodInStocks/loadlist={id}", method = RequestMethod.GET)
public ResponseEntity<byte[]> loadList(@PathVariable("id") Integer id) {
    byte[] bytes = pdfService.loadList(id);
    String filename = "report.pdf";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.valueOf("application/pdf"));
    headers.setContentLength(bytes.length);
    headers.setContentDispositionFormData("inline", filename);
    if (bytes.length == 0) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
    }
    return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
}

Angular Service:

function getLoadList(id){
    var deferred = $q.defer();
    $http.get(REST_SERVICE_URI+'loadlist='+id, {responseType : 'arraybuffer'})
        .then(
            function (response) {
                deferred.resolve(response);
            },
            function(errResponse){
                console.error('Error while fetching load list');
                deferred.reject(errResponse);
            }
        );
    return deferred.promise;
}

Angular Controller:

function loadList(documentId){
        GoodInStockService.getLoadList(documentId)
            .then(
                function(d){
                    var file = new Blob([d.data], {type: 'application/pdf'});
                    var url = window.URL || window.webkitURL;
                    var fileURL = url.createObjectURL(file);
                    window.open(fileURL);
                },
                function(errResponse){
                    console.error('Error while getting Load list');
                }
            )

    }

Finally, I get new tab in browser with next error "Failed to load PDF document" I tried to use different headers in rest controllers, create Blob from response, add 'produces="application/pdf' property in rest controller's method(by the way, in this way i got 406 error - why?)Also, i detect that arraybuffer(if i don't set length in header) and byte[] have different length, is it normal?

1

1 Answers

1
votes

Try to write directly to response and flush/close.

RequestMapping(value = "/goodInStocks/loadlist={id}", method = RequestMethod.GET)
public void loadList(@PathVariable("id") Integer id, HttpServletResponse response) {
  byte[] byteArray= pdfService.loadList(id);
  response.setStatus(HttpStatus.SC_OK);
  OutputStream os = response.getOutputStream();
  os.write(byteArray);
  os.flush();
  os.close();
}