java使用SFTP上传文件到资源服务器
本文实例为大家分享了java实现SFTP上传文件到资源服务器工具类,供大家参考,具体内容如下
首先得创建连接sftp服务器的公共类MySftp.java:
packagecn.test.util;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjava.util.Properties;
importjava.util.Vector;
importjavax.servlet.http.HttpServletRequest;
importcom.jcraft.jsch.Channel;
importcom.jcraft.jsch.ChannelSftp;
importcom.jcraft.jsch.JSch;
importcom.jcraft.jsch.Session;
importcom.jcraft.jsch.SftpException;
publicclassMySFTP{
/**
*连接sftp服务器
*@paramhost主机
*@paramport端口
*@paramusername用户名
*@parampassword密码
*/
publicChannelSftpconnect(Stringhost,intport,Stringusername,
Stringpassword){
ChannelSftpsftp=null;
try{
JSchjsch=newJSch();
jsch.getSession(username,host,port);
SessionsshSession=jsch.getSession(username,host,port);
sshSession.setPassword(password);
PropertiessshConfig=newProperties();
sshConfig.put("StrictHostKeyChecking","no");
sshSession.setConfig(sshConfig);
sshSession.connect();
Channelchannel=sshSession.openChannel("sftp");
channel.connect();
sftp=(ChannelSftp)channel;
}catch(Exceptione){
}
returnsftp;
}
/**
*上传文件
*
*@paramdirectory
*上传的目录
*@paramuploadFile
*要上传的文件
*@paramsftp
*/
publicvoidupload(Stringdirectory,StringuploadFile,ChannelSftpsftp){
try{
sftp.cd(directory);
Filefile=newFile(uploadFile);
sftp.put(newFileInputStream(file),file.getName());
}catch(Exceptione){
e.printStackTrace();
}
}
/**
*下载文件
*
*@paramdirectory
*下载目录
*@paramdownloadFile
*下载的文件
*@paramsaveFile
*存在本地的路径
*@paramsftp
*/
publicvoiddownload(Stringdirectory,StringdownloadFile,
StringsaveFile,ChannelSftpsftp){
try{
sftp.cd(directory);
Filefile=newFile(saveFile);
sftp.get(downloadFile,newFileOutputStream(file));
}catch(Exceptione){
e.printStackTrace();
}
}
/**
*删除文件
*
*@paramdirectory
*要删除文件所在目录
*@paramdeleteFile
*要删除的文件
*@paramsftp
*/
publicvoiddelete(Stringdirectory,StringdeleteFile,ChannelSftpsftp){
try{
sftp.cd(directory);
sftp.rm(deleteFile);
}catch(Exceptione){
e.printStackTrace();
}
}
publicvoiduploadSFTP(HttpServletRequestrequest,String[]uploadFiles)throwsException{
MySFTPmySFTP=newMySFTP();
SFTPUtilsFTPUtil=newSFTPUtil();
ChannelSftpsftp=null;
Sessionsession=null;
try{
sftp=mySFTP.connect(SystemConstants.SFTP_host,Integer.parseInt(SystemConstants.SFTP_port),SystemConstants.SFTP_username,SystemConstants.SFTP_password);
for(inti=0;i
上传图片时,调用SFTPUtil类中的uploadMultipartFile方法即可。
packagecn.test.util;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjava.util.Random;
importorg.springframework.web.multipart.MultipartFile;
importcom.jcraft.jsch.ChannelSftp;
importcom.jcraft.jsch.Session;
importcom.jcraft.jsch.SftpATTRS;
importcom.jcraft.jsch.SftpException;
/**文件上传工具类*/
publicclassSFTPUtil{
/**
*spring文件上传方法
**/
publicstaticStringuploadMultipartFile(MultipartFilefile,StringfileExt){
SFTPUtilsFTPUtil=newSFTPUtil();
StringoriginalFilename=file.getOriginalFilename();
//生成文件名
DateuploadTime=newDate();
SimpleDateFormatsdf=newSimpleDateFormat("yyyyMMdd");
Stringymd=sdf.format(uploadTime);
StringrelativePath=ymd+"/";
SimpleDateFormatdf=newSimpleDateFormat("yyyyMMddHHmmss");
StringfileName=df.format(uploadTime)+"_"+newRandom().nextInt(1000)+"."+fileExt;
//StringfileName=String.valueOf(newDate().getTime())+newRandom().nextInt(10000)+"."+originalFilename.substring(originalFilename.lastIndexOf(".")+1);
Stringdirectory=SystemConstants.SFTP_directory+relativePath;
ChannelSftpsftp=null;
Sessionsession=null;
try{
MySFTPmySFTP=newMySFTP();
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(Exceptione){
System.out.println("文件["+originalFilename+"]上传失败,堆栈轨迹如下:");
e.printStackTrace();
}finally{
try{
if(sftp!=null){
sftp.disconnect();
}
}catch(Exceptione){
e.printStackTrace();
}
try{
if(session!=null){
session.disconnect();
}
}catch(Exceptione){
e.printStackTrace();
}
}
StringreName=SystemConstants.SFTP_httpBaseUrl+relativePath+fileName;
returnreName;
}
/**
*创建目录
*@throwsException
*/
publicvoidcreateDir(Stringcreatepath,ChannelSftpsftp)throwsException{
try{
if(isDirExist(sftp,createpath)){
sftp.cd(createpath);
}
StringpathArry[]=createpath.split("/");
StringBufferfilePath=newStringBuffer("/");
for(Stringpath: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(SftpExceptione){
thrownewException(e.getMessage());
}
}
/**
*判断目录是否存在
*/
publicbooleanisDirExist(ChannelSftpsftp,Stringdirectory){
booleanisDirExistFlag=false;
try{
SftpATTRSsftpATTRS=sftp.lstat(directory);
isDirExistFlag=true;
returnsftpATTRS.isDir();
}catch(Exceptione){
if(e.getMessage().toLowerCase().equals("nosuchfile")){
isDirExistFlag=false;
}
}
returnisDirExistFlag;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。