js
function _es_preDownload(id, fileName) {
$.ajax({
url: ‘${ctx}/fdAttach/download‘,
type: ‘get‘,
async: false,
mimeType: ‘text/plain; charset=x-user-defined‘,//jq ajax请求文件流的方式 (起作用的重点)
data: {id: id},
success: function (data) {
if (data.code && data.code != Ajax.statusCode.ok) {
Dialog.error(data.message);
return;
}
Dialog.success("下载成功!");
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]);
var fileName = ‘PDF‘+new Date().getTime()+‘.pdf‘;
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());
}
ajax文件下载