Ho cercato di visualizzare il file pdf che sto ottenendo come un blob da una risposta $http.post
. Il pdf deve essere visualizzato all’interno dell’app usando per esempio.
Mi sono imbattuto in un paio di pali ma in qualche modo il mio esempio non sembra funzionare.
JS:
Secondo questo documento , ho continuato e ho provato …
$http.post('/postUrlHere',{myParams}).success(function (response) { var file = new Blob([response], {type: 'application/pdf'}); var fileURL = URL.createObjectURL(file); $scope.content = fileURL; });
Ora da quanto ho capito, fileURL
crea un URL temporaneo che il blog può utilizzare come riferimento.
HTML:
Non sono sicuro di come gestirlo in Angular, la situazione ideale sarebbe (1) assegnarlo a un ambito, (2) ‘preparare / ribuild’ il blob in un pdf (3) passarlo all’HTML usando perché voglio visualizzarlo all’interno dell’app.
Ho fatto ricerche per più di un giorno, ma in qualche modo non riesco a capire come funziona in Angular … E supponiamo che le librerie di visualizzatori di pdf non esistano.
Prima di tutto è necessario impostare responseType
su arraybuffer
. Questo è necessario se vuoi creare un blob dei tuoi dati. Vedi Sending_and_Receiving_Binary_Data . Quindi il tuo codice sarà simile a questo:
$http.post('/postUrlHere',{myParams}, {responseType:'arraybuffer'}) .success(function (response) { var file = new Blob([response], {type: 'application/pdf'}); var fileURL = URL.createObjectURL(file); });
La parte successiva è che devi usare il servizio $ sce per rendere il tuo URL angular. Questo può essere fatto in questo modo:
$scope.content = $sce.trustAsResourceUrl(fileURL);
Non dimenticare di iniettare il servizio $ sce .
Se tutto ciò è fatto, ora puoi incorporare il tuo pdf:
Io uso AngularJS v1.3.4
HTML:
Controller JS:
'use strict'; angular.module('xxxxxxxxApp') .controller('xxxxController', function ($scope, xxxxServicePDF) { $scope.downloadPdf = function () { var fileName = "test.pdf"; var a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; xxxxServicePDF.downloadPdf().then(function (result) { var file = new Blob([result.data], {type: 'application/pdf'}); var fileURL = window.URL.createObjectURL(file); a.href = fileURL; a.download = fileName; a.click(); }); }; });
Servizi JS:
angular.module('xxxxxxxxApp') .factory('xxxxServicePDF', function ($http) { return { downloadPdf: function () { return $http.get('api/downloadPDF', { responseType: 'arraybuffer' }).then(function (response) { return response; }); } }; });
Servizi Web Java REST – Spring MVC:
@RequestMapping(value = "/downloadPDF", method = RequestMethod.GET, produces = "application/pdf") public ResponseEntity getPDF() { FileInputStream fileStream; try { fileStream = new FileInputStream(new File("C:\\xxxxx\\xxxxxx\\test.pdf")); byte[] contents = IOUtils.toByteArray(fileStream); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("application/pdf")); String filename = "test.pdf"; headers.setContentDispositionFormData(filename, filename); ResponseEntity response = new ResponseEntity(contents, headers, HttpStatus.OK); return response; } catch (FileNotFoundException e) { System.err.println(e); } catch (IOException e) { System.err.println(e); } return null; }
i suggerimenti di michael funzionano come per me un fascino 🙂 Se sostituisci $ http.post con $ http.get, ricorda che il metodo .get accetta 2 parametri invece di 3 … questo è dove è sprecato il mio tempo …;)
Controller:
$http.get('/getdoc/' + $stateParams.id, {responseType:'arraybuffer'}) .success(function (response) { var file = new Blob([(response)], {type: 'application/pdf'}); var fileURL = URL.createObjectURL(file); $scope.content = $sce.trustAsResourceUrl(fileURL); });
vista:
Ho affrontato difficoltà usando “window.URL” con Opera Browser in quanto risulterebbe “non definito”. Inoltre, con window.URL, il documento PDF non è mai stato aperto in Internet Explorer e Microsoft Edge (rimarrebbe in attesa per sempre). Ho trovato la seguente soluzione che funziona in IE, Edge, Firefox, Chrome e Opera (non ho testato con Safari):
$http.post(postUrl, data, {responseType: 'arraybuffer'}) .success(success).error(failed); function success(data) { openPDF(data.data, "myPDFdoc.pdf"); }; function failed(error) {...}; function openPDF(resData, fileName) { var ieEDGE = navigator.userAgent.match(/Edge/g); var ie = navigator.userAgent.match(/.NET/g); // IE 11+ var oldIE = navigator.userAgent.match(/MSIE/g); var blob = new window.Blob([resData], { type: 'application/pdf' }); if (ie || oldIE || ieEDGE) { window.navigator.msSaveBlob(blob, fileName); } else { var reader = new window.FileReader(); reader.onloadend = function () { window.location.href = reader.result; }; reader.readAsDataURL(blob); } }
Fammi sapere se ha aiutato! 🙂
L’aggiunta di responseType alla richiesta creata da angular è davvero la soluzione, ma per me non ha funzionato finché non ho impostato responseType su blob , non su arrayBuffer. Il codice è auto esplicativo:
$http({ method : 'GET', url : 'api/paperAttachments/download/' + id, responseType: "blob" }).then(function successCallback(response) { console.log(response); var blob = new Blob([response.data]); FileSaver.saveAs(blob, getFileNameFromHttpResponse(response)); }, function errorCallback(response) { });
Ho faticato per gli ultimi giorni cercando di scaricare pdf e immagini, tutto quello che ero in grado di scaricare erano semplici file di testo.
La maggior parte delle domande ha gli stessi componenti, ma ci è voluto un po ‘per capire l’ordine giusto per farlo funzionare.
Grazie @Nikolay Melnikov, il tuo commento / risposta a questa domanda è stato quello che ha funzionato.
In poche parole, ecco la mia richiesta di backend del servizio AngularJS:
getDownloadUrl(fileID){ // //Get the download url of the file let fullPath = this.paths.downloadServerURL + fileId; // // return the file as arraybuffer return this.$http.get(fullPath, { headers: { 'Authorization': 'Bearer ' + this.sessionService.getToken() }, responseType: 'arraybuffer' }); }
Dal mio controller:
downloadFile(){ myService.getDownloadUrl(idOfTheFile).then( (response) => { //Create a new blob object let myBlobObject=new Blob([response.data],{ type:'application/pdf'}); //Ideally the mime type can change based on the file extension //let myBlobObject=new Blob([response.data],{ type: mimeType}); var url = window.URL || window.webkitURL var fileURL = url.createObjectURL(myBlobObject); var downloadLink = angular.element(''); downloadLink.attr('href',fileURL); downloadLink.attr('download',this.myFilesObj[documentId].name); downloadLink.attr('target','_self'); downloadLink[0].click();//call click function url.revokeObjectURL(fileURL);//revoke the object from URL }); }