@RequestMapping("/downloadFiles")
public void downloadFiles(HttpServletResponse response,HttpServletRequest request,String ids) {
try {
OutputStream out = null;
//先获取路径信息
String []idss = ids.split(",");
List<Map<String,Object>> list = this.service.downloadFiles(idss);
FTPUtil aFTPUtil = new FTPUtil();
byte[] temp = new byte[4096];
// byte[] bytes = new byte[4096];
ByteArrayOutputStream bao = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bao);
//根据路径去取流
for(int i = 0; i < list.size(); i++){
aFTPUtil.connectServer("10.0.6.181", 21, "Administrator", "123456", "/FTPServer");
temp = aFTPUtil.downloadFileByName((String)list.get(i).get("FILE_NAME"));
ZipEntry ze = null;
ze = new ZipEntry((String)list.get(i).get("FILE_NAME"));
ze.setSize(temp.length);
ze.setTime(System.currentTimeMillis());
zos.putNextEntry(ze);
zos.write(temp);
}
zos.close();
response.setContentType("application/x-msdownload");
//发送html消息头
response.setHeader("Content-Disposition", "attachment;filename="
+ new String(("file.zip").getBytes("gbk"), "iso-8859-1"));
out = response.getOutputStream();
out.write(bao.toByteArray());
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
}
}
/**
* 将指定的远程文件数据写到bytes
*
* @param remoteFileName
* @param out
* @throws Exception
*/
public byte[] downloadFileByName(String remoteFileName) throws Exception {
InputStream inputStream = null;
try {
if(StringUtils.isBlank(remoteFileName)){
return null;
}
String foundName = null;
FTPFile[] files = ftpClient.listFiles();
String ftpFileName = "";
for (FTPFile file : files) {
ftpFileName = file.getName();
if (file.isFile()
&& remoteFileName.equals(ftpFileName)) {
foundName = file.getName();
break;
}
}
if(foundName != null && !foundName.equals("")){
String encodedFoundFileName = CommonUtil.getString(foundName,
CoreConstants.ENCODING_GBK, CoreConstants.ENCODING_ISO8859_1);
inputStream = ftpClient.retrieveFileStream(encodedFoundFileName);
if(inputStream==null){
throw new Exception("Fail to download file from ftp server.");
}
log.debug("inputStream.available():"+inputStream.available());
byte[] rtnDataArr = CommonUtil.inputStream2Bytes(inputStream);
if(!ftpClient.completePendingCommand()) {
throw new Exception("File transfer failed!Fail to download file from ftp server.");
}
return rtnDataArr;
}
return null;
} catch (Exception e) {
log.error("download file failed.", e);
throw new Exception(e);
} finally {
try {
if(inputStream!=null){
inputStream.close();
}
} catch (IOException e1) {
inputStream = null;
}
try {
closeServer();
} catch (Exception e) {
}
}
}