工具推荐:
IIS7服务器管理工具是一款windows全系、Linux系统下链接并操控VPS、VNC、FTP等远程服务器、云服务器。
界面简单明了,操作易上手,功能强大,支持批量导入服务器,并批量打开,多窗口化管理,除此之外,加载本地硬盘、硬盘映射、加载服务器的声音,远程声卡读取等,完全实现各类场景使用,对于FTP链接界面,朋友FTP定时上传,定时下载(也可以说定时上传下载 定时备份),对于经常使用FTP的小伙伴来说,非常适用。
工具支持自动更新,压缩包只有7.62M,方便简洁,一步到位。
下载地址:http://yczm.iis7.com/?tscc
正文开始:
1.大概思路:
2. 先根据ID查询出来url
@RequestMapping(value="test1", produces = "text/plain;charset=UTF-8")
public void test2(HttpServletRequest request ,HttpServletResponse response){
try {
List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(" select url from tb_work_record where FIND_IN_SET(wr_id,'1,2') ");
FTPUtils ftp = new FTPUtils();
ftp.connectServer("172.168.31.321", 21, "111", "2222");//连接ftp
String filepath[] = new String[queryForList.size()];//ftp文件路径
String localfilepath[] = new String[queryForList.size()];//web文件路径
for (int i = 0; i < queryForList.size(); i++) {
String url = queryForList.get(i).get("url").toString();
filepath[i]=url;
//为下载到web服务器的文件的名称重新起名
String fileName = StringUtils.substringAfterLast(url, "/");
String suffix = StringUtils.substringAfterLast( fileName, ".") ;
String newName = StringUtils.substringBeforeLast( fileName, "_") ;
String name= URLDecoder.decode(newName+"_"+id.nextId()+"."+suffix,"UTF-8") ;
String path= "E://upload//"+name;
localfilepath[i]=path;
}
for (int i = 0; i < queryForList.size(); i++) {
//将ftp服务器的文件下载到web服务器
ftp.download(filepath[i], localfilepath[i]);
}
ftp.closeConnect();
//在web服务器上找到下载好的文件进行压缩
zip(request, response, localfilepath);
//循环删除web服务器上的文件
for (int i = 0; i < localfilepath.length; i++) {
boolean deleteExcel = ExcelUtils2.deleteExcel(localfilepath[i]);
System.out.println(deleteExcel);
}
} catch (Exception e) {
e.printStackTrace();
}
}
3.ftp工具类
/**
*
*/
package com.ufc.utils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.io.*;
import java.net.SocketException;
/**
* @author lll 2018年11月27日 上午9:39:00
*/
public class FTPUtils {
/**
*
* 本地文件名
*/
private String localfilename;
/**
*
* 远程文件名
*/
private String remotefilename;
/**
*
* FTP客户端
*/
private FTPClient ftpClient;
/**
* 服务器连接
*
* @param ip
* 服务器IP
* @param port
* 服务器端口
* @param user
* 用户名
* @param password
* 密码
* @throws FtpProtocolException
*
*/
public void connectServer(String ip, int port, String user, String password) throws Exception {
try {
/* ******连接服务器的两种方法****** */
// 第一种方法
/*
* ftpClient =FtpClient.create(); ftpClient.connect(new
* InetSocketAddress(ip, port));
*/
// 第二种方法
ftpClient = new FTPClient();
ftpClient.connect(ip, port);// 连接FTP服务器
ftpClient.login(user, password);// 登陆FTP服务器
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
System.out.println("未连接到FTP,用户名或密码错误。");
ftpClient.disconnect();
} else {
System.out.println("FTP连接成功。");
}
} catch (SocketException e) {
e.printStackTrace();
System.out.println("FTP的IP地址可能错误,请正确配置。");
} catch (IOException e) {
e.printStackTrace();
System.out.println("FTP的端口错误,请正确配置。");
}
}
/**
* 关闭连接
*
*/
public void closeConnect() {
try {
ftpClient.logout();
System.out.println("disconnect success");
} catch (IOException ex) {
System.out.println("not disconnect");
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
/**
*
* 上传文件
*
* @param localFile
* 本地文件
* @param remoteFile
* 远程文件
* @throws FtpProtocolException
*/
public void upload(String localFile, String remoteFile) throws Exception {
boolean success = false;
try {
int reply;
reply = ftpClient.getReplyCode();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
}
ftpClient.setControlEncoding("UTF-8"); // 中文支持
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
FileInputStream in = new FileInputStream(new File(localFile));
ftpClient.changeWorkingDirectory(remoteFile.substring(0, remoteFile.lastIndexOf(File.separator) + 1));
ftpClient.storeFile(remoteFile.substring(remoteFile.lastIndexOf(File.separator) + 1, remoteFile.length()),
in);
in.close();
success = true;
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* 下载文件
*
* @param remoteFile
* 远程文件路径(服务器端)
* @param localFile
* 本地文件路径(客户端)
* @throws FtpProtocolException
*
*/
public void download(String remoteFile, String localFile) throws Exception {
try {
ftpClient.setControlEncoding("UTF-8"); // 中文支持
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(remoteFile.substring(0, remoteFile.lastIndexOf(File.separator) + 1));
File localFiles = new File(localFile);
OutputStream os = new FileOutputStream(localFiles);
ftpClient.retrieveFile( remoteFile.substring(remoteFile.lastIndexOf(File.separator) + 1, remoteFile.length()), os);
os.close();
System.out.println("download success");
} catch (FileNotFoundException e) {
System.out.println("没有找到" + localFile + "文件");
e.printStackTrace();
} catch (SocketException e) {
System.out.println("连接FTP失败.");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件读取错误。");
e.printStackTrace();
}
}
/**
* 函数入口
*
* @param agrs
* @throws FtpProtocolException
*/
public static void main(String agrs[]) throws Exception {
String filepath[] = { "/test.txt", "/www/test.txt", "/www/yyy/test.txt" };
String localfilepath[] = { "/Users/lll/Downloads/test.txt", "/Users/lll/Downloads/test1.txt","/Users/lll/Downloads/test2.txt" };
FTPUtils ftp = new FTPUtils();
// /*
// * 使用默认的端口号、用户名、密码以及根目录连接FTP服务器
// */
try {
ftp.connectServer("10.211.55.4", 21, "TFTP", "Root123");
} catch (Exception e) {
e.printStackTrace();
}
// 下载
for (int i = 0; i < filepath.length; i++) {
try {
ftp.download(filepath[i], localfilepath[i]);
} catch (Exception e) {
e.printStackTrace();
}
}
ftp.closeConnect();
// String localfile = "/Users/lll/Downloads/table.txt";
// String remotefile = "/records.txt";
// // 上传
// try
// {
// ftp.upload(localfile, remotefile);
// } catch (FtpProtocolException e)
// {
// e.printStackTrace();
// }
}
public static void dl() {
}
}
4.在web服务器上找到下载好的文件进行压缩
public void zip(HttpServletRequest request, HttpServletResponse response, String[] filePaths) {
try {
String zipBasePath = "E://upload";
long nextId = id.nextId();
String zipName = nextId + ".zip";
String zipFilePath = zipBasePath + "//" + zipName;
System.out.println(zipFilePath);
File zip = new File(zipFilePath);
if (!zip.exists()) {
zip.createNewFile();
}
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip));
// 从ftp服务器复制文件到web服务器
zipFile(zipBasePath, zipName, zipFilePath, filePaths, zos);
zos.close();
// 从服务器下载压缩文件
template(response, zipFilePath);
new File(zipFilePath).delete();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 压缩文件
* @param zipBasePath 临时压缩文件基础路径
* @param zipName 临时压缩文件名称
* @param zipFilePath 临时压缩文件完整路径
* @param filePaths 需要压缩的文件路径集合
* @throws IOException
*/
private void zipFile(String zipBasePath, String zipName, String zipFilePath, String[] filePaths, ZipOutputStream zos) throws IOException {
// 循环读取文件路径集合,获取每一个文件的路径
for (String filePath : filePaths) {
File inputFile = new File(filePath); // 根据文件路径创建文件
if (inputFile.exists()) { // 判断文件是否存在
if (inputFile.isFile()) { // 判断是否属于文件,还是文件夹
// 创建输入流读取文件
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
inputFile.delete();
// 将文件写入zip内,即将文件进行打包
zos.putNextEntry(new ZipEntry(URLDecoder.decode( StringUtils.substringAfterLast(filePath, "/") ,"UTF-8") ));
// 写入文件的方法,同上
int size = 0;
byte[] buffer = new byte[102400]; // 设置读取数据缓存大小
while ((size = bis.read(buffer)) > 0) {
zos.write(buffer, 0, size);
}
// 关闭输入输出流
zos.closeEntry();
bis.close();
}
}
}
}
5.调用浏览器下载zip
/**
* 调用浏览器下载
* @param response
* @param downLoadPath
*/
public void template(HttpServletResponse response ,String downLoadPath){
try {
String fileName=downLoadPath.substring(downLoadPath.lastIndexOf("/")+1);
byte[] buffer=null;
buffer = ExcelUtils.downFileByte(downLoadPath) ;
String fileSuffixName= fileName.substring(fileName.lastIndexOf(".")+1);
response.reset(); //清除缓存
response.setContentType("application/" +fileSuffixName + ";" +"charset = UTF-8"); //设置字符集和文件后缀名
String name=id.nextId()+"";
name = new String(name.getBytes(), "ISO-8859-1");
response.setHeader("Content-Disposition","attachment; filename=" +name+"."+fileSuffixName); // 设置文件名称
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (Exception e) {
e.printStackTrace();
Log4jUtil.getLog4jUtil().error("下载zip文件异常"+e.getMessage());
}
}
注意 :ftp报错可以用ftp.getReplyCode()查看返回码以便确认异常.