2017-05-17 4 views
0

私はこの問題について数日を費やし、数百の記事を読んでいました。しかし、私はまだそれを解決することはできません。Spring RESTとAngularjsを使用してPDFを表示

RESTコントローラー:

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

角度サービス:

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

角度コントローラー:

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

    } 

最後に、次のエラーでブラウザの新しいタブが表示される 残りのコントローラで異なるヘッダを使用しようとしましたが、レスポンスからBlobを作成し、残りのコントローラのメソッドで 'produce = "application/pdf"ところで、私は406エラーを持っている - なぜ?)arraybuffer(私はヘッダーの長さを設定しない場合)とバイト[]は異なる長さを持っていることを検出、それは正常ですか?

答えて

1

応答とフラッシュ/閉じるに直接書き込むようにしてください。

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

ありがとうございます!それは動作します!私のバリアントがなぜそうでないのか説明できますか?私は間違ったArrayBufferを取得することを理解します。しかし、なぜ? –

+0

私はストリームに直接書き込むのではなく、あなたのケースのバイトをシリアル化しようとしていると思います。だから、あなたの場合のブラウザはファイルではなくバイトを持つJSONです。 – StanislavL

関連する問題