错误方式:
$.ajax({
url: '/remote/sftp/download/post?host=',
type: 'POST',
// dataType: 'json',
contentType: 'application/json',
data: JSON.stringify([]),
responseType: "blob"
}).done((res) => {
console.log(typeof res); //string
//...
});
这种方式保存的文件是不能打开的,console.log(typeof(data))会看到是string类型
原因是jquery将返回的数据转换为了string,不支持blob类型.
正确方式:
使用原生xhr
var url = 'remote/sftp/download?host=';
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = "blob"; // 返回类型blob
xhr.onload = function () {
// 请求完成
if (this.status === 200) {
// 返回200
var blob = this.response;
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function (e) {
// 转换完成,创建一个a标签用于下载
var a = document.createElement('a');
a.download = 'log.zip';
a.href = e.target.result;
$("body").append(a);
a.click();
$(a).remove();
}
}
};
// 发送ajax请求
xhr.send(JSON.stringify([]));
========================================================================
后台接口:post类型 返回二进制字节流
@RequestMapping(value = "/sftp/download", method = RequestMethod.POST)
public void downloadFile2(@RequestParam String path, HttpServletResponse response) throws BaseAppException, IOException {
//简写一下 注意捕获异常
byte[] bytes = ....; //字节流来源 文件等
response.setCharacterEncoding("utf-8");
response.setContentType("application/octet-stream;charset=utf-8");
response.setContentLength(bytes.length);
response.setHeader("Content-Disposition", "attachment;fileName=" + targetName);
OutputStream os = new BufferedOutputStream(response.getOutputStream());
os.write(bytes);
os.flush();
os.close();
}