关于FTP上传文件到云服务器上的工具类
首先导入两个包 pom.xml
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.49</version>
</dependency>
或者你可以去下载频道下载
java类
public class FTP {
private static String rootName = "连接服务器的登录名";
private static String host = "主机名";
private static String password = "连接密码";
private static String rootPath = "/opt/images";//存放图片的根目录
/**
* 获取连接
*/
public static ChannelSftp getChannel() throws Exception{
JSch jsch = new JSch();
Session sshSession = jsch.getSession(rootName,host,22);//->ssh root@host:port
sshSession.setPassword(password);//密码
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;
return sftp;
}
/**
* ftp上传图片
* @param inputStream 图片io流
* @param imagePath 路径,不存在就创建目录
* @param imagesName 图片名称
*/
public static void putImages(InputStream inputStream,String imagePath,String imagesName){
try {
ChannelSftp sftp = getChannel();
String path = rootPath+imagePath+"/";
createDir(path,sftp);
sftp.put(inputStream, path + imagesName);
System.out.println("创建成功");
sftp.quit();
sftp.exit();
} catch (Exception e1) {
e1.printStackTrace();
}
}
/**
* 创建目录
*/
public static void createDir(String path,ChannelSftp sftp) throws SftpException{
String[] folders = path.split("/");
sftp.cd("/");
for ( String folder : folders ) {
if ( folder.length() > 0 ) {
try {
sftp.cd( folder );
}catch ( SftpException e ) {
sftp.mkdir( folder );
sftp.cd( folder );
}
}
}
}
/**
* 删除图片
* @param inputStream
* @param imagesName
*/
public static void delImages(String imagesName){
try {
ChannelSftp sftp = getChannel();
String path = rootPath + imagesName;
sftp.rm(path);
sftp.quit();
sftp.exit();
} catch (Exception e) {
e.printStackTrace();
}
}
}