溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java實(shí)現(xiàn)上傳文件到服務(wù)器指定目錄的方法

發(fā)布時間:2020-08-03 10:49:31 來源:億速云 閱讀:583 作者:小豬 欄目:編程語言

這篇文章主要講解了Java實(shí)現(xiàn)上傳文件到服務(wù)器指定目錄的方法,內(nèi)容清晰明了,對此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會有幫助。

前言需求

使用freemarker生成的靜態(tài)文件,統(tǒng)一存儲在某個服務(wù)器上。本來一開始打算使用ftp實(shí)現(xiàn)的,奈何老連接不上,改用jsch。畢竟有現(xiàn)成的就很舒服,在此介紹給大家。

具體實(shí)現(xiàn)

引入的pom

<dependency>
	<groupId>ch.ethz.ganymed</groupId>
	<artifactId>ganymed-ssh3</artifactId>
	<version>262</version>
</dependency>

<dependency>
	<groupId>com.jcraft</groupId>
	<artifactId>jsch</artifactId>
	<version>0.1.55</version>
</dependency>

建立實(shí)體類

public class ResultEntity {

  private String code;

  private String message;

  private File file;
  
  public ResultEntity(){}
  
	public ResultEntity(String code, String message, File file) {
		super();
		this.code = code;
		this.message = message;
		this.file = file;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}
  
}

public class ScpConnectEntity {
  private String userName;
  private String passWord;
  private String url;
  private String targetPath;

  public String getTargetPath() {
    return targetPath;
  }

  public void setTargetPath(String targetPath) {
    this.targetPath = targetPath;
  }

  public String getUserName() {
    return userName;
  }

  public void setUserName(String userName) {
    this.userName = userName;
  }

  public String getPassWord() {
    return passWord;
  }

  public void setPassWord(String passWord) {
    this.passWord = passWord;
  }

  public String getUrl() {
    return url;
  }

  public void setUrl(String url) {
    this.url = url;
  }

}

建立文件上傳工具類

@Configuration

@Configuration
public class FileUploadUtil {

  @Value("${remoteServer.url}")
  private String url;

  @Value("${remoteServer.password}")
  private String passWord;

  @Value("${remoteServer.username}")
  private String userName;

  @Async
  public ResultEntity uploadFile(File file, String targetPath, String remoteFileName) throws Exception{
    ScpConnectEntity scpConnectEntity=new ScpConnectEntity();
    scpConnectEntity.setTargetPath(targetPath);
    scpConnectEntity.setUrl(url);
    scpConnectEntity.setPassWord(passWord);
    scpConnectEntity.setUserName(userName);

    String code = null;
    String message = null;
    try {
      if (file == null || !file.exists()) {
        throw new IllegalArgumentException("請確保上傳文件不為空且存在!");
      }
      if(remoteFileName==null || "".equals(remoteFileName.trim())){
        throw new IllegalArgumentException("遠(yuǎn)程服務(wù)器新建文件名不能為空!");
      }
      remoteUploadFile(scpConnectEntity, file, remoteFileName);
      code = "ok";
      message = remoteFileName;
    } catch (IllegalArgumentException e) {
      code = "Exception";
      message = e.getMessage();
    } catch (JSchException e) {
      code = "Exception";
      message = e.getMessage();
    } catch (IOException e) {
      code = "Exception";
      message = e.getMessage();
    } catch (Exception e) {
      throw e;
    } catch (Error e) {
      code = "Error";
      message = e.getMessage();
    }
    return new ResultEntity(code, message, null);
  }


  private void remoteUploadFile(ScpConnectEntity scpConnectEntity, File file,
                 String remoteFileName) throws JSchException, IOException {

    Connection connection = null;
    ch.ethz.ssh3.Session session = null;
    SCPOutputStream scpo = null;
    FileInputStream fis = null;

    try {
      createDir(scpConnectEntity);
    }catch (JSchException e) {
      throw e;
    }

    try {
      connection = new Connection(scpConnectEntity.getUrl());
      connection.connect();

      if(!connection.authenticateWithPassword(scpConnectEntity.getUserName(),scpConnectEntity.getPassWord())){
        throw new RuntimeException("SSH連接服務(wù)器失敗");
      }
      session = connection.openSession();

      SCPClient scpClient = connection.createSCPClient();

      scpo = scpClient.put(remoteFileName, file.length(), scpConnectEntity.getTargetPath(), "0666");
      fis = new FileInputStream(file);

      byte[] buf = new byte[1024];
      int hasMore = fis.read(buf);

      while(hasMore != -1){
        scpo.write(buf);
        hasMore = fis.read(buf);
      }
    } catch (IOException e) {
      throw new IOException("SSH上傳文件至服務(wù)器出錯"+e.getMessage());
    }finally {
      if(null != fis){
        try {
          fis.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if(null != scpo){
        try {
          scpo.flush();
//          scpo.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if(null != session){
        session.close();
      }
      if(null != connection){
        connection.close();
      }
    }
  }


  private boolean createDir(ScpConnectEntity scpConnectEntity ) throws JSchException {

    JSch jsch = new JSch();
    com.jcraft.jsch.Session sshSession = null;
    Channel channel= 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 (JSchException e) {
      e.printStackTrace();
      throw new JSchException("SFTP連接服務(wù)器失敗"+e.getMessage());
    }
    ChannelSftp channelSftp=(ChannelSftp) channel;
    if (isDirExist(scpConnectEntity.getTargetPath(),channelSftp)) {
      channel.disconnect();
      channelSftp.disconnect();
      sshSession.disconnect();
      return true;
    }else {
      String pathArry[] = scpConnectEntity.getTargetPath().split("/");
      StringBuffer filePath=new StringBuffer("/");
      for (String path : pathArry) {
        if (path.equals("")) {
          continue;
        }
        filePath.append(path + "/");
        try {
          if (isDirExist(filePath.toString(),channelSftp)) {
            channelSftp.cd(filePath.toString());
          } else {
            // 建立目錄
            channelSftp.mkdir(filePath.toString());
            // 進(jìn)入并設(shè)置為當(dāng)前目錄
            channelSftp.cd(filePath.toString());
          }
        } catch (SftpException e) {
          e.printStackTrace();
          throw new JSchException("SFTP無法正常操作服務(wù)器"+e.getMessage());
        }
      }
    }
    channel.disconnect();
    channelSftp.disconnect();
    sshSession.disconnect();
    return true;
  }

  private boolean isDirExist(String directory,ChannelSftp channelSftp) {
    boolean isDirExistFlag = false;
    try {
      SftpATTRS sftpATTRS = channelSftp.lstat(directory);
      isDirExistFlag = true;
      return sftpATTRS.isDir();
    } catch (Exception e) {
      if (e.getMessage().toLowerCase().equals("no such file")) {
        isDirExistFlag = false;
      }
    }
    return isDirExistFlag;
  }
}

屬性我都寫在Spring的配置文件里面了。將這個類托管給spring容器。

看完上述內(nèi)容,是不是對Java實(shí)現(xiàn)上傳文件到服務(wù)器指定目錄的方法有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI