js
function _es_preDownload(id, fileName) {
$.ajax({
url: '${ctx}/fdAttach/download',
type: 'post',
async: false,
mimeType: 'text/plain; charset=x-user-defined',//jq ajax请求文件流的方式 (起作用的重点)
data: {id: id},
success: function (data) {
var rawLength = data.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for (i = 0; i < rawLength; i++) {
array[i] = data.charCodeAt(i) & 0xff;
}
//上面是把后台请求到的文件流进行转化为符合的流
var blob = new Blob([array]);
try {
var res = $.parseJSON(data);
if (res.code && res.code != Ajax.statusCode.ok) {
// 中文乱码问题
blob.text().then(function (res) {
res = $.parseJSON(res);
Dialog.error(res.message);
return;
});
}
return;
}
catch (e) {
}
Dialog.success("下载成功!");
if ('download' in document.createElement('a')) {
//非IE下载
const elink = document.createElement('a');
elink.download = fileName;
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href);
document.body.removeChild(elink);
}
else {
navigator.msSaveBlob(blob, fileName);
}
}
});
return false;
}
java
@RequestMapping("/download")
public void download(String id, HttpServletResponse response)
throws Exception {
FileInfo fileInfo = fdAttachService.download(id);
InputStream is = fileInfo.getInputStream();
response.setContentType("application/force-download");
IOUtils.copy(is, response.getOutputStream());
}