Java如何实现上传文件到服务器指定目录
前言需求
使用freemarker生成的静态文件,统一存储在某个服务器上。本来一开始打算使用ftp实现的,奈何老连接不上,改用jsch。毕竟有现成的就很舒服,在此介绍给大家。
具体实现
引入的pom
ch.ethz.ganymed ganymed-ssh2 262 com.jcraft jsch 0.1.55
建立实体类
publicclassResultEntity{
privateStringcode;
privateStringmessage;
privateFilefile;
publicResultEntity(){}
publicResultEntity(Stringcode,Stringmessage,Filefile){
super();
this.code=code;
this.message=message;
this.file=file;
}
publicStringgetCode(){
returncode;
}
publicvoidsetCode(Stringcode){
this.code=code;
}
publicStringgetMessage(){
returnmessage;
}
publicvoidsetMessage(Stringmessage){
this.message=message;
}
publicFilegetFile(){
returnfile;
}
publicvoidsetFile(Filefile){
this.file=file;
}
}
publicclassScpConnectEntity{
privateStringuserName;
privateStringpassWord;
privateStringurl;
privateStringtargetPath;
publicStringgetTargetPath(){
returntargetPath;
}
publicvoidsetTargetPath(StringtargetPath){
this.targetPath=targetPath;
}
publicStringgetUserName(){
returnuserName;
}
publicvoidsetUserName(StringuserName){
this.userName=userName;
}
publicStringgetPassWord(){
returnpassWord;
}
publicvoidsetPassWord(StringpassWord){
this.passWord=passWord;
}
publicStringgetUrl(){
returnurl;
}
publicvoidsetUrl(Stringurl){
this.url=url;
}
}
建立文件上传工具类
@Configuration
@Configuration
publicclassFileUploadUtil{
@Value("${remoteServer.url}")
privateStringurl;
@Value("${remoteServer.password}")
privateStringpassWord;
@Value("${remoteServer.username}")
privateStringuserName;
@Async
publicResultEntityuploadFile(Filefile,StringtargetPath,StringremoteFileName)throwsException{
ScpConnectEntityscpConnectEntity=newScpConnectEntity();
scpConnectEntity.setTargetPath(targetPath);
scpConnectEntity.setUrl(url);
scpConnectEntity.setPassWord(passWord);
scpConnectEntity.setUserName(userName);
Stringcode=null;
Stringmessage=null;
try{
if(file==null||!file.exists()){
thrownewIllegalArgumentException("请确保上传文件不为空且存在!");
}
if(remoteFileName==null||"".equals(remoteFileName.trim())){
thrownewIllegalArgumentException("远程服务器新建文件名不能为空!");
}
remoteUploadFile(scpConnectEntity,file,remoteFileName);
code="ok";
message=remoteFileName;
}catch(IllegalArgumentExceptione){
code="Exception";
message=e.getMessage();
}catch(JSchExceptione){
code="Exception";
message=e.getMessage();
}catch(IOExceptione){
code="Exception";
message=e.getMessage();
}catch(Exceptione){
throwe;
}catch(Errore){
code="Error";
message=e.getMessage();
}
returnnewResultEntity(code,message,null);
}
privatevoidremoteUploadFile(ScpConnectEntityscpConnectEntity,Filefile,
StringremoteFileName)throwsJSchException,IOException{
Connectionconnection=null;
ch.ethz.ssh2.Sessionsession=null;
SCPOutputStreamscpo=null;
FileInputStreamfis=null;
try{
createDir(scpConnectEntity);
}catch(JSchExceptione){
throwe;
}
try{
connection=newConnection(scpConnectEntity.getUrl());
connection.connect();
if(!connection.authenticateWithPassword(scpConnectEntity.getUserName(),scpConnectEntity.getPassWord())){
thrownewRuntimeException("SSH连接服务器失败");
}
session=connection.openSession();
SCPClientscpClient=connection.createSCPClient();
scpo=scpClient.put(remoteFileName,file.length(),scpConnectEntity.getTargetPath(),"0666");
fis=newFileInputStream(file);
byte[]buf=newbyte[1024];
inthasMore=fis.read(buf);
while(hasMore!=-1){
scpo.write(buf);
hasMore=fis.read(buf);
}
}catch(IOExceptione){
thrownewIOException("SSH上传文件至服务器出错"+e.getMessage());
}finally{
if(null!=fis){
try{
fis.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=scpo){
try{
scpo.flush();
//scpo.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=session){
session.close();
}
if(null!=connection){
connection.close();
}
}
}
privatebooleancreateDir(ScpConnectEntityscpConnectEntity)throwsJSchException{
JSchjsch=newJSch();
com.jcraft.jsch.SessionsshSession=null;
Channelchannel=null;
try{
sshSession=jsch.getSession(scpConnectEntity.getUserName(),scpConnectEntity.getUrl(),22);
sshSession.setPassword(scpConnectEntity.getPassWord());
sshSession.setConfig("StrictHostKeyChecking","no");
sshSession.connect();
channel=sshSession.openChannel("sftp");
channel.connect();
}catch(JSchExceptione){
e.printStackTrace();
thrownewJSchException("SFTP连接服务器失败"+e.getMessage());
}
ChannelSftpchannelSftp=(ChannelSftp)channel;
if(isDirExist(scpConnectEntity.getTargetPath(),channelSftp)){
channel.disconnect();
channelSftp.disconnect();
sshSession.disconnect();
returntrue;
}else{
StringpathArry[]=scpConnectEntity.getTargetPath().split("/");
StringBufferfilePath=newStringBuffer("/");
for(Stringpath:pathArry){
if(path.equals("")){
continue;
}
filePath.append(path+"/");
try{
if(isDirExist(filePath.toString(),channelSftp)){
channelSftp.cd(filePath.toString());
}else{
//建立目录
channelSftp.mkdir(filePath.toString());
//进入并设置为当前目录
channelSftp.cd(filePath.toString());
}
}catch(SftpExceptione){
e.printStackTrace();
thrownewJSchException("SFTP无法正常操作服务器"+e.getMessage());
}
}
}
channel.disconnect();
channelSftp.disconnect();
sshSession.disconnect();
returntrue;
}
privatebooleanisDirExist(Stringdirectory,ChannelSftpchannelSftp){
booleanisDirExistFlag=false;
try{
SftpATTRSsftpATTRS=channelSftp.lstat(directory);
isDirExistFlag=true;
returnsftpATTRS.isDir();
}catch(Exceptione){
if(e.getMessage().toLowerCase().equals("nosuchfile")){
isDirExistFlag=false;
}
}
returnisDirExistFlag;
}
}
属性我都写在Spring的配置文件里面了。将这个类托管给spring容器。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。