java的sftp文件传输_java使用SFTP上传文件到资源服务器方法详解

java使用SFTP上传文件到资源服务器

本文实例为大家分享了java实现SFTP上传文件到资源服务器工具类,供大家参考,具体内容如下

首先得创建连接sftp服务器的公共类MySftp.java:

package cn.test.util;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Properties;

import java.util.Vector;

import javax.servlet.http.HttpServletRequest;

import com.jcraft.jsch.Channel;

import com.jcraft.jsch.ChannelSftp;

import com.jcraft.jsch.JSch;

import com.jcraft.jsch.Session;

import com.jcraft.jsch.SftpException;

public class MySFTP {

/**

* 连接sftp服务器

* @param host 主机

* @param port 端口

* @param username 用户名

* @param password 密码

*/

public ChannelSftp connect(String host, int port, String username,

String password) {

ChannelSftp sftp = null;

try {

JSch jsch = new JSch();

jsch.getSession(username, host, port);

Session sshSession = jsch.getSession(username, 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();

sftp = (ChannelSftp) channel;

} catch (Exception e) {

}

return sftp;

}

/**

* 上传文件

*

* @param directory

* 上传的目录

* @param uploadFile

* 要上传的文件

* @param sftp

*/

public void upload(String directory, String uploadFile, ChannelSftp sftp) {

try {

sftp.cd(directory);

File file = new File(uploadFile);

sftp.put(new FileInputStream(file), file.getName());

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 下载文件

*

* @param directory

* 下载目录

* @param downloadFile

* 下载的文件

* @param saveFile

* 存在本地的路径

* @param sftp

*/

public void download(String directory, String downloadFile,

String saveFile, ChannelSftp sftp) {

try {

sftp.cd(directory);

File file = new File(saveFile);

sftp.get(downloadFile, new FileOutputStream(file));

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 删除文件

*

* @param directory

* 要删除文件所在目录

* @param deleteFile

* 要删除的文件

* @param sftp

*/

public void delete(String directory, String deleteFile, ChannelSftp sftp) {

try {

sftp.cd(directory);

sftp.rm(deleteFile);

} catch (Exception e) {

e.printStackTrace();

}

}

public void uploadSFTP(HttpServletRequest request,String[] uploadFiles) throws Exception {

MySFTP mySFTP = new MySFTP();

SFTPUtil sFTPUtil =new SFTPUtil();

ChannelSftp sftp = null;

Session session = null;

try {

sftp = mySFTP.connect(SystemConstants.SFTP_host, Integer.parseInt(SystemConstants.SFTP_port), SystemConstants.SFTP_username, SystemConstants.SFTP_password);

for (int i = 0; i < uploadFiles.length; i++) {

Date uploadTime = new Date();

String url=request.getSession().getServletContext().getRealPath("").replaceAll("\\\\", "/");

String uploadFile =url.substring(0, url.lastIndexOf("/"))+uploadFiles[i];

// String saveFile="";

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

String ymd = sdf.format(uploadTime);

String relativePath = ymd + "/";

String directory = SystemConstants.SFTP_directory+ relativePath;

sFTPUtil.createDir(directory, sftp);

mySFTP.upload(directory, uploadFile, sftp);

sftp.cd(directory);

}

} catch (Exception e) {

e.printStackTrace();

}finally{

try {

if(sftp != null) {

sftp.disconnect();

}

} catch (Exception e) {

e.printStackTrace();

}

try {

if(session != null) {

session.disconnect();

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

/**

* 列出目录下的文件

*

* @param directory

* 要列出的目录

* @param sftp

* @return

* @throws SftpException

*/

@SuppressWarnings("rawtypes")

public Vector listFiles(String directory, ChannelSftp sftp)

throws SftpException {

return sftp.ls(directory);

}

}

上传图片时,调用SFTPUtil类中的uploadMultipartFile方法即可。

package cn.test.util;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Random;

import org.springframework.web.multipart.MultipartFile;

import com.jcraft.jsch.ChannelSftp;

import com.jcraft.jsch.Session;

import com.jcraft.jsch.SftpATTRS;

import com.jcraft.jsch.SftpException;

/**文件上传工具类*/

public class SFTPUtil {

/**

* spring文件上传方法

* */

public static String uploadMultipartFile(MultipartFile file,String fileExt) {

SFTPUtil sFTPUtil =new SFTPUtil();

String originalFilename = file.getOriginalFilename();

//生成文件名

Date uploadTime = new Date();

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

String ymd = sdf.format(uploadTime);

String relativePath = ymd+"/";

SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

String fileName = df.format(uploadTime) + "_" + new Random().nextInt(1000) + "." + fileExt;

// String fileName = String.valueOf(new Date().getTime())+ new Random().nextInt(10000)+"."+originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

String directory=SystemConstants.SFTP_directory+relativePath;

ChannelSftp sftp =null;

Session session = null;

try {

MySFTP mySFTP = new MySFTP();

sftp = mySFTP.connect(SystemConstants.SFTP_host, Integer.parseInt(SystemConstants.SFTP_port), SystemConstants.SFTP_username, SystemConstants.SFTP_password);

session = sftp.getSession();

sFTPUtil.createDir(directory, sftp);

sftp.cd(directory);

sftp.put(file.getInputStream(), fileName);

sftp.disconnect();

sftp.getSession().disconnect();

} catch (Exception e) {

System.out.println("文件[" + originalFilename + "]上传失败,堆栈轨迹如下:");

e.printStackTrace();

}finally{

try {

if(sftp != null) {

sftp.disconnect();

}

} catch (Exception e) {

e.printStackTrace();

}

try {

if(session != null) {

session.disconnect();

}

} catch (Exception e) {

e.printStackTrace();

}

}

String reName=SystemConstants.SFTP_httpBaseUrl+relativePath+fileName;

return reName;

}

/**

* 创建目录

* @throws Exception

*/

public void createDir(String createpath, ChannelSftp sftp) throws Exception {

try {

if (isDirExist(sftp, createpath)) {

sftp.cd(createpath);

}

String pathArry[] = createpath.split("/");

StringBuffer filePath = new StringBuffer("/");

for (String path : pathArry) {

if (path.equals("")) {

continue;

}

filePath.append(path + "/");

if (isDirExist(sftp, filePath.toString())) {

sftp.cd(filePath.toString());

} else {

// 建立目录

sftp.mkdir(filePath.toString());

// 进入并设置为当前目录

sftp.cd(filePath.toString());

}

}

sftp.cd(createpath);

} catch (SftpException e) {

throw new Exception(e.getMessage());

}

}

/**

* 判断目录是否存在

*/

public boolean isDirExist(ChannelSftp sftp,String directory) {

boolean isDirExistFlag = false;

try {

SftpATTRS sftpATTRS = sftp.lstat(directory);

isDirExistFlag = true;

return sftpATTRS.isDir();

} catch (Exception e) {

if (e.getMessage().toLowerCase().equals("no such file")) {

isDirExistFlag = false;

}

}

return isDirExistFlag;

}

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持码农之家。

以上就是本次给大家分享的关于java的全部知识点内容总结,大家还可以在下方相关文章里找到相关文章进一步学习,感谢大家的阅读和支持。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值