java下载文件功能,导出的时候会下载到浏览器默认下载文件夹里,360浏览器会弹出一个保存文件的弹出框
//下载导出报表
//JS
function downloadExport(filename){
window.location.href=”/order-center/ui/spm/downloadExport.do?filename=”+filename;
}
/**
* 查询导出报表: http://localhost:8080/order-center/ui/spm/downloadExport.do
* key module
*/
@RequestMapping(value = "downloadExport.do", method = RequestMethod.GET)
public void downloadExport(
@RequestParam(value = "filename", required = false) String filename,
HttpServletResponse response) {
File pf = new File(SpmRest.class.getResource("/").getFile());
FileInputStream fis=null;
OutputStream ostream=null;
try {
// if (!getUser().getShopid().equals(EGlobal.TOP_SHOP_ID)) {
shopId = getUser().getShopid();
// shopId = spmService.getUserShopList(getUser(),shopId);
// }
String dirPath = pf.getParentFile().getParentFile().getAbsolutePath()+ File.separator + "exportfile";
File dirFile = new File(dirPath);
if (!dirFile.exists())
dirFile.mkdir();
File file = new File(dirFile.getAbsolutePath() + File.separator
+ filename);
if (!file.exists()) {//查询服务器有没有文件,没有则冲FTP下载
boolean downloadExport = spmService.downloadExport(dirPath, filename);
if(!downloadExport){
return ;
}
}
fis = new FileInputStream(file);
ostream = response.getOutputStream();
response.setContentType("application/ms-excel");
response.setHeader("Content-disposition", "attachment; filename="+ filename);
byte[] b = new byte[1024];
int len = fis.read(b);
while (len > 0) {
ostream.write(b, 0, len);
len = fis.read(b);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
ostream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 从ftp下载报表
* @throws SftpException
*/
public boolean downloadExport(String dirPath, String filename) {
boolean flag = false;
ChannelSftp sftp = null;
SFTPUtilTools sftptool = null;//连接FTP,自定义类,网上很多示例
try{
sftptool = new SFTPUtilTools();
sftp = sftptool.connectChannel(FGlobal.EXPORT_HOSTNAME, FGlobal.EXPORT_USERNAME, FGlobal.EXPORT_PASSWORD);
if (sftp == null) {
logger.warn("无效链接或链接失败");
return flag;
}
logger.info("**************开始下载导出报表EXPORT**************");
sftp.cd(FGlobal.EXPORT_REC);//进入ftp下载文件夹
File file = new File(dirPath+File.separator+filename);//导出到服务器文件
sftp.get(filename,new FileOutputStream(file));//下载文件
System.out.println("文件更新成功:" + file.getName());
flag = true;
logger.info("**************下载文件成功**************");
}catch(Exception e){
logger.error(e);
}finally{
sftptool.closeChannel(sftp);
}
return flag;
}