思路
1.首先连接ftp服务器
2.连接到服务器之后如何上传文件
3.上传后如何获取文件
4.文件格式是图片如何展示到客户端浏览器
5.服务端代码如何接收客户端的文件以及如何返回响应信息给浏览器
主要jar包依赖文件
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
<!-- jsch 所依赖的jar包 -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jzlib</artifactId>
<version>1.1.1</version>
</dependency>
public class SftpUtils {
private static final Logger log = LoggerFactory.getLogger(SftpUtils.class);
private static ChannelSftp sftp;
public static Properties properties = LoadProperties.getProperties("/config/sftp.properties");
private static Channel channel;
private static Session sshSession;
/**
* 登陆SFTP服务器
* @return
*/
public static boolean getConnect() throws Exception{
log.info("进入SFTP====");
boolean result = false;
JSch jsch = new JSch();
//获取sshSession 账号-ip-端口,从properties文件中获取连接ftp服务器的相关信息
sshSession =jsch.getSession(properties.getProperty("user"), properties.getProperty("ip"), Integer.parseInt(properties.getProperty("port")));
//添加密码
sshSession.setPassword(properties.getProperty("password"));
Properties sshConfig = new Properties();
//严格主机密钥检查
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
//开启sshSession链接
sshSession.connect();
//获取sftp通道
channel = sshSession.openChannel("sftp");
//开启
channel.connect();
sftp = (ChannelSftp) channel;
result = true;
return result;
}
/**
* 文件上传
* @param inputStream 上传的文件输入流
* @param fileCategory 存储文件目录分类
* @return
*/
public static String upload(InputStream inputStream, String fileCategory, String fileName) throws Exception{
String destinationPath = properties.getProperty("destinationPath")+fileCategory;
try {
sftp.cd(destinationPath);
//获取随机文件名
fileName = UUID.randomUUID().toString().replace("-", "") + fileName;
//文件名是 随机数加文件名的后5位
sftp.