我想下载一个异步文件。我有一个工作的同步方法,从url调用时运行:
<a th:href="@{'download/' + ${person.number}}">download</a>
和
@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,但它没有改变任何东西。我错过了什么?