前端代码
function downloadFileByAjax(fileUrl, filePath,index) {
if(index == null || index == undefined){
index = 0;
}
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', fileUrl+"?index="+index, true);
xmlHttp.onreadystatechange = function (){
if (xmlHttp.readyState === 4) {
var fileName = decodeURI(xmlHttp.getResponseHeader("fileName"));
var tempIndex = xmlHttp.getResponseHeader("index");
console.log("fileName:"+fileName);
console.log("tempIndex:"+tempIndex);
if (xmlHttp.status < 300 && xmlHttp.status >= 200) {
if(tempIndex == null || tempIndex == undefined ){
if (index > 0){
alert("下载成功!")
}
return false;
}
saveStreamToFile(xmlHttp.responseBody, filePath+fileName);
downloadFileByAjax(fileUrl,filePath,tempIndex);
} else {
alert("下载失败!");
}
}
};
xmlHttp.send();
}
function saveStreamToFile(stream, filePath) {
saveContentToFile(stream, filePath, '1');
}
function saveContentToFile(content,filePath,type) {
var adodbstream = new ActiveXObject('ADODB.Stream');
adodbstream.Mode = '3';
adodbstream.Type = type;
adodbstream.Open();
if (type === '1') {
adodbstream.Write(content);
} else {
adodbstream.WriteText(content);
}
var fn1 = 'SaveTo';
var fn2 = 'File';
adodbstream[fn1+fn2](filePath, 2);
adodbstream.Close();
}
后台代码
@ResponseBody
@RequestMapping(value = "/testDownloadByJS", method = RequestMethod.GET)
public void testDownloadByJS(HttpServletRequest request,HttpServletResponse response){
try{
String i = request.getParameter("index") == null ? "" : request.getParameter("index");
if (StringUtil.isBlank(i) ){
return ;
}
int index = Integer.parseInt(i);
File file = new File("\\opt\\temp\\aaa.doc");
File file1 = new File("\\opt\\temp\\bbb.doc");
File file2 = new File("\\opt\\temp\\ccc.doc");
List<File> fileList = new ArrayList<>();
fileList.add(file);
fileList.add(file1);
fileList.add(file2);
if (index > fileList.size()-1){
return ;
}
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileList.get(index)));
response.reset();
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setHeader("fileName", URLEncoder.encode(fileList.get(index).getName(), "UTF-8"));
response.setHeader("index",index+1+"");
ServletOutputStream outputStream = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(outputStream);
int len = 0;
byte[] buf = new byte[10 * 1024];
while( (len=bis.read(buf, 0, buf.length)) != -1){
bos.write(buf, 0, len);
}
bis.close();
bos.flush();
bos.close();
}catch (Exception e){
log.error(e.getMessage(),e);
log.warn(e.getMessage());
}
}