1、ftp上传工具类
package com.zhjg.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.web.multipart.MultipartFile;
/**
* 当端口号为21时使用FTP
*
* 配置文件示例:
* sftp.host = IP
* sftp.username = username
* sftp.password = password
* sftp.port = 21
* sftp.path = /directory/...
*
* @author zhjg
*
*/
public class FTPUtils {
// ftp配置放在属性文件中
private static Properties ftpConfig;
static {
ftpConfig = new Properties();
try {
ftpConfig.load(FTPUtils.class.getClassLoader()
.getResourceAsStream("ftp.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* springmvc文件上传
*
* @param file
* @return 保存在服务器的文件名
*/
public static String uploadFile(MultipartFile file) {
String filename = null;
try {
filename = uploadFile(file.getOriginalFilename(),
file.getInputStream());
} catch (IOException e) {
e.printStackTrace();
return null;
}
return filename;
}
/**
* 通用文件上传
*
* @param originalFilename
* @param is
* @return 保存在服务器的文件名
*/
public static String uploadFile(String originalFilename, InputStream is) {
String filename = generateFileUUIDName(originalFilename);
FTPClient ftpClient = null;
try {
ftpClient = connect();
//以二进制的形式上传,文件不会被改动
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
ftpClient.storeFile(filename, is);
is.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
closeClient(ftpClient);
return filename;
}
/**
* 下载文件 将指定要下载的文件解析到指定的输出流对象 并返回服务器上保存的文件的文件名(带有扩展名)
* 参数中的filename是前端传递的参数(没有扩展名)
*
* @param filename
* @param os
* @return 保存在服务器的文件名
*/
public static String downFile(String filename, OutputStream os) {
FTPClient ftpClient = null;
try {
ftpClient = connect();
//以二进制的形式下载,文件不会被改动
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
FTPFile[] ftpFiles = ftpClient.listFiles();
for (FTPFile file : ftpFiles) {
if (file.getName().contains(filename)) {
filename = file.getName();
ftpClient.retrieveFile(filename, os);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
closeClient(ftpClient);
return filename;
}
/**
* 删除ftp上不在列表中的文件:
* 文件记录会存放在数据库中,当数据库中记录删除时, ftp服务器上对应的文件也要删除
*
* @param filenames
* @return true:成功;false:失败
*/
public static boolean deleteFiles(List<String> filenames) {
FTPClient ftpClient = null;
try {
ftpClient = connect();
// 获取ftp当前目录的文件列表
FTPFile[] ftpFiles = ftpClient.listFiles();
// 删除标记位
boolean isDelete = true;
for (FTPFile file : ftpFiles) {
isDelete = true;
for (String filename : filenames) {
if (filename.equalsIgnoreCase(file.getName())) {
isDelete = false;
}
}
if (isDelete) {
ftpClient.deleteFile(file.getName());
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
closeClient(ftpClient);
return true;
}
/**
* 连接FTP服务器 返回连接对象 若使用对象池来维护,可在此方法中borrow连接
*
* @return
* @throws IOException
* @throws SocketException
*/
public static FTPClient connect() throws SocketException, IOException {
String host = ftpConfig.getProperty("ftp.host");
int port = Integer.parseInt(ftpConfig.getProperty("ftp.port"));
String username = ftpConfig.getProperty("ftp.username");
String password = ftpConfig.getProperty("ftp.password");
String path = ftpConfig.getProperty("ftp.path");
FTPClient ftpClient = new FTPClient();
ftpClient.connect(host, port);
ftpClient.login(username, password);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
return null;
}
// 切换到path指定的目录
ftpClient.changeWorkingDirectory(path);
return ftpClient;
}
/**
* 退出登录状态 关闭连接
*
* @param ftpClient
*/
public static void closeClient(FTPClient ftpClient) {
try {
if (ftpClient != null) {
ftpClient.logout();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ftpClient != null && ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
/**
* 生成保存在服务器上的文件名
*
* @param originalFilename
* @return
*/
public static String generateFileUUIDName(String originalFilename) {
return UUID.randomUUID().toString().replaceAll("-", "")
+ originalFilename.substring(originalFilename.indexOf("."));
}
}
2、sftp上传工具类
package com.zhjg.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import java.util.UUID;
import java.util.Vector;
import org.springframework.web.multipart.MultipartFile;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
/**
* 当端口号为22时使用SFTP
*
* 配置文件示例:
* sftp.host = IP
* sftp.username = username
* sftp.password = password
* sftp.port = 22
* sftp.path = /directory/...
*
* @author zhjg
*
*/
public class SFTPUtils {
// sftp配置放在属性文件中
private static Properties sftpConfig;
static {
sftpConfig = new Properties();
try {
//加载class根目录下的sftp配置文件
sftpConfig.load(SFTPUtils.class.getClassLoader()
.getResourceAsStream("sftp.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取sftp连接
*
* @return
* @throws JSchException
*/
public static ChannelSftp getChannel() throws JSchException {
String host = sftpConfig.getProperty("sftp.host");
int port = Integer.parseInt(sftpConfig.getProperty("sftp.port"));
String username = sftpConfig.getProperty("sftp.username");
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(sftpConfig.getProperty("sftp.password"));
session.connect();
ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
return channel;
}
public static void close(Channel channel) {
Session session = null;
if (channel != null) {
session = channel.getSession();
channel.disconnect();
session.disconnect();
}
}
/**
* springmvc文件上传
*
* @param file
* @return
* @throws IOException
* @throws SftpException
* @throws JSchException
*/
public static String uploadFile(MultipartFile file) {
InputStream is = null;
try {
is = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return uploadFile(file.getOriginalFilename(), is);
}
/**
* 文件上传
*
* @param originalFilename
* :本地文件名
* @param is
* :上传文件流
* @return filename:保存在服务器上的文件名
* @throws JSchException
* @throws SftpException
*/
public static String uploadFile(String originalFilename, InputStream is) {
return uploadFile(originalFilename, is,
sftpConfig.getProperty("sftp.path"));
}
/**
* 文件上传
*
* @param originalFilename
* :本地文件名
* @param is
* :上传文件流
* @param path
* :文件保存路径
* @return filename:保存在服务器上的文件名
* @throws JSchException
* @throws SftpException
*/
public static String uploadFile(String originalFilename, InputStream is,
String path) {
ChannelSftp channel = null;
String filename = generateFileUUIDName(originalFilename);
try {
channel = getChannel();
channel._put(is, path + filename, null, 0);
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
close(channel);
return filename;
}
/**
* 文件下载
*
* @param filename
* :待下载的文件名(没有扩展名)
* @param os
* :响应的输出流
* @return filename :待下载的文件名(扩展名)
* @throws JSchException
* @throws SftpException
*/
public static String downFile(String filename, OutputStream os) {
return downFile(filename, os, sftpConfig.getProperty("sftp.path"));
}
/**
* 文件下载
*
* @param filename
* :待下载的文件名(没有扩展名)
* @param os
* :响应的输出流
* @return filename :待下载的文件名(扩展名)
* @throws SftpException
* @throws JSchException
*/
@SuppressWarnings("rawtypes")
public static String downFile(String filename, OutputStream os, String path) {
ChannelSftp channel = null;
try {
channel = getChannel();
Vector ls = channel.ls(path);
if (ls != null && ls.size() > 0) {
for (int i = 0; i < ls.size(); i++) {
LsEntry entry = (LsEntry) ls.get(i);
if (entry.getFilename().contains(filename)) {
filename = entry.getFilename();
channel.get(path + filename, os, null);
close(channel);
return filename;
}
}
}
} catch (SftpException e) {
e.printStackTrace();
} catch (JSchException e) {
e.printStackTrace();
}
close(channel);
return null;
}
/**
* 生成保存在服务器上的文件名
*
* @param originalFilename
* @return
*/
public static String generateFileUUIDName(String originalFilename) {
return UUID.randomUUID().toString().replaceAll("-", "")
+ originalFilename.substring(originalFilename.indexOf("."));
}
}