Display blob (.pdf) w aplikacji kątowej

Próbuję wyświetlić plik pdf, który otrzymuję jako blob z odpowiedzi $http.post. Plik pdf musi być wyświetlany w aplikacji za pomocą <embed src> na przykład.

Natknąłem się na kilka postów, ale jakoś mój przykład nie działa.

JS:

Według tego doktora , poszedłem dalej i próbowałem...

$http.post('/postUrlHere',{myParams}).success(function (response) {
 var file = new Blob([response], {type: 'application/pdf'});
 var fileURL = URL.createObjectURL(file);
 $scope.content = fileURL;
});

Teraz z tego co rozumiem, fileURL tworzy tymczasowy adres URL, który blog może wykorzystać jako Referencja.

HTML:

<embed src="{{content}}" width="200" height="200"></embed>
Nie jestem pewien, jak sobie z tym poradzić w Angular, idealną sytuacją byłoby (1) przypisanie go do zakresu, (2) 'przygotuj / Przebuduj" blob do pliku pdf (3) przekaż go do HTML za pomocą <embed>, ponieważ chcę go wyświetlić w aplikacji. [6]}badam już ponad dzień, ale jakoś nie mogę zrozumieć, jak to działa w Angular... I załóżmy, że biblioteki przeglądarki pdf są nie było wyjścia.
Author: picciano, 2014-02-07

6 answers

Najpierw musisz ustawić responseType na arraybuffer. Jest to wymagane, jeśli chcesz utworzyć blob swoich danych. Zobacz Sending_and_Receiving_Binary_Data . Więc Twój kod będzie wyglądał tak:

$http.post('/postUrlHere',{myParams}, {responseType:'arraybuffer'})
  .success(function (response) {
       var file = new Blob([response], {type: 'application/pdf'});
       var fileURL = URL.createObjectURL(file);
});

Następna część jest taka, że musisz użyć usługi $sce, aby angular zaufał twojemu url. Można to zrobić w ten sposób:

$scope.content = $sce.trustAsResourceUrl(fileURL);

Nie zapomnij wprowadzić Usługi $sce .

Jeśli to wszystko jest zrobione, możesz teraz osadzić swój plik pdf:

<embed ng-src="{{content}}" style="width:200px;height:200px;"></embed>
 186
Author: michael,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-12 15:22:53

Używam AngularJS v1. 3. 4

HTML:

<button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>

Kontroler 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();
            });
        };
});

JS services:

angular.module('xxxxxxxxApp')
    .factory('xxxxServicePDF', function ($http) {
        return {
            downloadPdf: function () {
            return $http.get('api/downloadPDF', { responseType: 'arraybuffer' }).then(function (response) {
                return response;
            });
        }
    };
});

Java REST Web Services - Spring MVC:

@RequestMapping(value = "/downloadPDF", method = RequestMethod.GET, produces = "application/pdf")
    public ResponseEntity<byte[]> 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<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
            return response;
        } catch (FileNotFoundException e) {
           System.err.println(e);
        } catch (IOException e) {
            System.err.println(e);
        }
        return null;
    }
 29
Author: sgrillon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-26 07:03:14

Sugestie Michaela działają jak urok dla mnie :) Jeśli zastąpisz $http.post z $http.get, pamiętaj, że .metoda get akceptuje 2 parametry zamiast 3... tutaj marnuje się mój czas... ;)

Kontroler:

$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);
});

Widok:

<object ng-show="content" data="{{content}}" type="application/pdf" style="width: 100%; height: 400px;"></object>
 19
Author: Jan Tchärmän,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-07 08:22:39

Napotkałem trudności używając " window.URL "z przeglądarką Opera jako wynik "undefined". Również z oknem.URL, dokument PDF nigdy nie został otwarty w przeglądarce Internet Explorer i Microsoft Edge(pozostanie on w nieskończoność). Wymyśliłem następujące rozwiązanie, które działa w IE, Edge, Firefox, Chrome i Opera (nie testowałem z 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);
    }
}
Daj znać, jeśli to pomogło! :)
 10
Author: Manuel Hernandez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-08 21:41:18

Dodanie responseType do żądania, które jest wykonane z angular, jest rzeczywiście rozwiązaniem, ale dla mnie nie zadziałało, dopóki nie ustawiłem responseType na blob, a nie na arrayBuffer. Kod jest sam wyjaśniający:

    $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) {   
        });
 6
Author: ancab,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-27 08:20:45

Zmagałem się przez ostatnie kilka dni próbując pobrać pliki PDF i obrazy,wszystko, co udało mi się pobrać, to proste pliki tekstowe.

Większość pytań ma te same składniki, ale znalezienie odpowiedniej kolejności zajęło trochę czasu.

Dziękuję @ Nikolay Melnikov, twój komentarz/odpowiedź na to pytanie było co sprawiło, że to działa.

W skrócie, oto moje wywołanie backendowe usługi 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'
    });
  }

Z mojego kontrolera:

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('<a></a>');
      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
    });
}
 0
Author: Javier Carbajal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-25 06:05:03