2017-11-27 172 views
0

ファイルasyncをダウンロードしたいと思います。AJAXとSpring Bootでファイルをダウンロードする

<a th:href="@{'download/' + ${person.number}}">download</a> 

と::私はURLから呼び出されたときに実行される作業の同期方法持って

@RequestMapping(value = "/download/{number}", method = RequestMethod.GET) 
public ResponseEntity<byte[]> downloadFile(@PathVariable Long number) throws Exception { 

byte[] array = Files.readAllBytes(file.toPath()); 
String fileName = "attachment; filename="+number+".xls"; 

HttpHeaders responseHeaders = new HttpHeaders(); 
responseHeaders.set("charset", "utf-8"); 
responseHeaders.setContentType(MediaType.valueOf("text/html")); 
responseHeaders.setContentLength(array.length); 
responseHeaders.set("Content-disposition", fileName); 

return new ResponseEntity<byte[]>(array, responseHeaders, HttpStatus.OK); 
} 

は今、私はjQueryの/ AJAXを経由して、それを呼び出すしたいと思いますが、私が持っているものです。

<button class="btn" id="downloadButton" name="23">download</button> 

$('#downloadButton').click(function() { 

    var urlToCall = "/download/"+this.name; 

    $.ajax({ 
     type:'GET', 
     url: urlToCall, 
     success: function(data){ 

     } 
    }); 
}); 

このコードはJavaメソッドを呼び出してからJS成功関数を呼び出しますが、ファイルには がダウンロードされていません。 @ResponseBodyで試したが、何も変わっていない。私は何を取りこぼしたか?

答えて

0

問題はサーバー側ではありません。問題はクライアントコードにあります。

GETリクエストをこのようにすると、レスポンスオブジェクト内のデータが取得されます。

代わりに、ダウンロードが開始されるようにブラウザでURLを参照する必要があります。

あり、それを行うには、いくつかの方法がありますが、あなたはjQueryを使用していることを見て、最も簡単には次のようになります。

$('#downloadButton').attr({target: '_blank', href: "/download/something.xls"}); 

さらに詳細:Download File Using Javascript/jQuery

関連する問題