整个项目用的是spring Boot和layui
jar放在Ubuntu下运行,
然后我在Ubuntu下访问web页面下载文件,只下载一次这个正常。
如下图
然后,我在windows下访问web进行文件下载就会下载两次
如下图
下面是具体代码
JS的代码
$.ajax({
type:"POST",
url:"/result/checkFile",
data : JSON.stringify(data),
dataType:"json",
contentType:"application/json",
async: false,
success:function (dataMap) {
if(dataMap.code==200){
downLoad("/result/download?fileName="+dataMap.fileName)
}else if (dataMap.code==404){
layer.msg("数据获取异常!");
}else if(dataMap.code==400){
layer.open({
title: '提 示',
content: '登录失效',
end: function() {
window.location.href="/login";
}
});
}
}
});
//传入参数src为文件地址
function downLoad (src) {
var download_file= {}
if (typeof(download_file.iframe) == "undefined") {
var iframe = document.createElement("iframe");
download_file.iframe = iframe;
document.body.appendChild(download_file.iframe);
}
download_file.iframe.src = src
download_file.iframe.style.display = "none";
}
java后端的代码
@ResponseBody
@RequestMapping(value = "/download")
public void downloadFile(HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException {
String fileName = (String) request.getParameter("fileName")+".xls"; //下载的文件名
//System.out.printf((String) map.get("begin"));
// 如果文件名不为空,则进行下载
if (fileName != null) {
//设置文件路径
String realPath = "upload/excel/"; //服务器路径
File file = new File(realPath, fileName);
System.out.printf("下载 "+file.getAbsolutePath());
// 如果文件名存在,则进行下载
if (file.exists()) {
// 配置文件下载
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 下载文件能正常显示中文
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 实现文件下载
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("Download successfully!");
}
catch (Exception e) {
System.out.println("Download failed!");
}
finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}else {
System.out.println("找不到文件");
}
}
}