#水·滴# 如何經過jquery Ajax 下載 spring rest 的字節數組對象:jquery
return ResponseEntity.ok()
.contentType(new MediaType(MediaType.APPLICATION_OCTET_STREAM, Charset.forName("UTF-8")))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + new String("成果報告.docx".getBytes("UTF-8"), "GB2312"))
.body(bos.toByteArray());
複製代碼
Spring 默認返回二進制對象,JQuery默認接收string,所以須要修改JQuery的接收類型:ajax
$.ajax({
type: 'get',
url: " http://10.10.190.222:9080/QualityCheck/dev/excel/statisExport/2",
headers: {
'Authorization': "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1ZGllbmNlIjoid2ViIiwiY3JlYXRlZCI6MTU2Njk1NjMxNjcxNSwiZXhwIjoxNTY3NTYxMTE2fQ.OSXLq81QyG1N2JaYXQbjFCUcEPN85xnLvqF7RrtAM_MGEChoSLmc0sDmLJlg4RZLwTyCTOuCCljl6WdIgpuvnA"
},
// xhrFields: {
// responseType: 'blob'
// },
// 當出錯時是text,所以不能直接設blob
xhr: function () {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 2) {
if (xhr.status == 200) {
xhr.responseType = "blob";
} else {
xhr.responseType = "text";
}
}
};
return xhr;
},
success: function (response, msg, xhr) {
console.log("success", response)
// FileSaver.saveAs(response, "t.xlsx")
var blob = new Blob([response], { type: 'application/octet-stream' });
var filename = "成果彙總表.xlsx";
var download_URL = URL.createObjectURL(response);
// debugger;
if (filename) {
var a_link = document.createElement('a');
a_link.rel = 'noopener';
if (typeof a_link.download == 'undefined') {
window.location = download_URL;
} else {
a_link.href = download_URL;
a_link.download = filename;
document.body.appendChild(a_link);
a_link.click();
}
} else {
window.location = download_URL;
}
setTimeout(function () {
URL.revokeObjectURL(download_URL);
}, 10000);
},
error: function (error) {
console.log("error ", error)
}
});
複製代碼