Freddy Freddy - 2 months ago 194
Javascript Question

AngularJS open PDF in new tab and change filename/url

In my AngularJS Website I want to load .pdf documents and show them in new browser tabs. The following code works, but some things bother me:

The createdObjectURL is set as the title of the document and browser tab. That means my documents are always titled as somthing like

01d9bdca-9af2-43f0-a83f-f36fd82fd72
which is not really decent. And the visible URL isn't good, too. Instead of
blob:http://localhost:8080/01d9bdca-9af2-43f0-a83f-f36fd82fd72f
it would be better to have the URL I call in the service.js.

I tried to handle the filename in the HttpHeaders, but that has no effect at all :(

Another strange thing: if I do not specify the
{responseType: "arraybuffer"}
, the PDF-Title is displayed correctly. But there is no content, the document is empty.

Any help on how to change the filename and/or URL would be appreciated. Thank you.

JS Controller

DocumentService.getDocument().then(function(response) {
$window.open(response, '_blank');
});


JS Service

return {
getDocument : function () {
return $http.get("document", {responseType: "arraybuffer"})
.then(function(response) {
var file = new Blob([response.data], {type: "application/pdf"});
var fileURL = URL.createObjectURL(file);
return fileURL;
}
}
}


Spring MVC ReST-Service

@RequestMapping(value = "/document", method = RequestMethod.GET)
public ResponseEntity<byte[]> getDocument(){
try {
File file = new File("C:\\pathToFile.pdf");
byte[] fileContent = new byte[(int) file.lenth()];

HttpHeaders heraders = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = "NameOfFile.pdf";
headers.setContentDispositionFormData(filename, filename); //doesn't change anything

fileContent = File.readAllBytes(file.toPath());

ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(fileContent, headers, HttpStatus.OK);

return response;
} catch (FileNotFoundException e ) {
System.err.println("File not found " + e);
} catch (IOException e ) {
System.err.pringln("Error while reading file " + e);
}
}


Short version:
When a PDF file is loaded as a byte array and displayed it in a new browser tab with the AngularJS $window directive: Is there a good possibility to change the filename and URL?

Answer

Open a new tab with the url to the resource returning the byte-array! Something like:

$window.open('localhost:xxx/api/document', '_blank');