1.前台发送请求
//下载模版 jQuery 中的方法
function _uploadModel(){
window.location = "${basePath}docAndInfra/uploadModel.do";
}
2.后台接收请求
/**
* 下载excel表格的模版
* @param request
* @param response
@
Constants.DOCANDINFRA_EXPORTEXCEL 是Excel表格模版在FTP上 的下载地址
* @throws Exception
*/
@RequestMapping("uploadModel.do")
public void uploadModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
String fileName=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"Excel模版"+".zip";
queryAndUseService.upLoadInfo(Constants.DOCANDINFRA_EXPORTEXCEL,fileName,request,response);
}
3、server 成处理请求
/**
* 下载附件
* @param accessoryInfo
* @param fileName
* @param request
* @param response
* @throws Exception
*/
@Transactional
public void upLoadInfo(String accessoryInfo,String fileName,HttpServletRequest request,HttpServletResponse response)throws Exception{
Path ftpPath = null;
FTPClient ftp = null;
// 设置消息头
String contentType = "application/octet-stream";
response.setContentType("text/html;charset=UTF-8");
response.setContentType(contentType);
request.setCharacterEncoding("UTF-8");
response.setHeader("Content-disposition", "attachment; filename="
+ new String(fileName.getBytes("utf-8"), "ISO8859-1"));
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
ZipOutputStream zos = new ZipOutputStream(bos);
// 设置流编码方式
zos.setEncoding("utf-8");
String filePath =accessoryInfo.replace("\\", "/");
String ftpPathCode = filePath.substring(0, filePath.indexOf("/"));
ftpPath = Constants.initPathMap.get(ftpPathCode);
StringBuffer fileNames=new StringBuffer();
fileNames.append("下载文件").append("\\");
if(ftpPath!=null){
ftp= FTPUtils.getFtpClient(ftpPath.getServerPath(), ftpPath.getPort(), ftpPath.getUsername(), ftpPath.getPassword());
ftp.enterLocalPassiveMode();
String rootPath=accessoryInfo.substring(filePath.indexOf("/")+1);
Boolean flag=ftp.changeWorkingDirectory(rootPath);
if(flag){
FTPFile[] list = ftp.listFiles();
Integer listCount=list.length;
for(int i=0;i<listCount;i++){
FTPFile f=list[i];
//在火狐浏览器上处理文件名乱码的问题
zos.putNextEntry(new ZipEntry(fileNames.toString() + new String(f.getName().getBytes("iso8859-1"), "GBK")));
ftp.retrieveFile(f.getName(), zos);
zos.closeEntry();
}
}else{
zos.putNextEntry(new ZipEntry(fileNames.toString() + "文件不存在"));
ftp.retrieveFile("文件不存在", zos);
zos.closeEntry();
}
}
zos.close();
}