最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時(shí)間:2020年04月16日 15:04:34   投稿:yaominghui  
這篇文章主要介紹了Java如何實(shí)現(xiàn)上傳文件到服務(wù)器指定目錄,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

前言需求

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

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

引入的pom

<dependency>
	<groupId>ch.ethz.ganymed</groupId>
	<artifactId>ganymed-ssh2</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("請(qǐng)確保上傳文件不為空且存在!");
      }
      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.ssh2.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ù)器出錯(cuò)"+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的配置文件里面了。將這個(gè)類托管給spring容器。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 解決IDEA中同項(xiàng)目引用報(bào)紅問題

    解決IDEA中同項(xiàng)目引用報(bào)紅問題

    在IDEA中,如果項(xiàng)目引用報(bào)紅,可能是因?yàn)镮DEA的引用緩存問題,可以通過File->Invalidate Caches/Restart清空緩存并重建索引來解決,這個(gè)方法可以幫助解決同項(xiàng)目中引用找不到的問題,恢復(fù)正常的項(xiàng)目引用,消除報(bào)紅
    2024-09-09
  • Java8新特性:函數(shù)式編程

    Java8新特性:函數(shù)式編程

    Java8最新引入函數(shù)式編程概念,該項(xiàng)技術(shù)可以大大提升編碼效率,本文會(huì)對(duì)涉及的對(duì)象等進(jìn)行兩種方法的對(duì)比,對(duì)新技術(shù)更直白的看到變化,更方便學(xué)習(xí)
    2021-06-06
  • java實(shí)現(xiàn)文件拷貝的七種方式

    java實(shí)現(xiàn)文件拷貝的七種方式

    這篇文章主要介紹了java實(shí)現(xiàn)文件拷貝的七種方式,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-02-02
  • 基于Java將Excel科學(xué)計(jì)數(shù)法解析成數(shù)字

    基于Java將Excel科學(xué)計(jì)數(shù)法解析成數(shù)字

    這篇文章主要介紹了基于Java將Excel科學(xué)計(jì)數(shù)法解析成數(shù)字,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-09-09
  • 解決mybatis-plus通用mapper調(diào)用報(bào)錯(cuò):Invalid bound statement

    解決mybatis-plus通用mapper調(diào)用報(bào)錯(cuò):Invalid bound statement

    這篇文章主要介紹了解決mybatis-plus通用mapper調(diào)用報(bào)錯(cuò):Invalid bound statement的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • JMM核心概念之Happens-before原則

    JMM核心概念之Happens-before原則

    關(guān)于Java并發(fā)的通信機(jī)制是基于共享內(nèi)存實(shí)現(xiàn)的,線程之間共享程序的公共狀態(tài),通過寫-讀內(nèi)存中的公共狀態(tài)進(jìn)行隱式通信,這對(duì)程序員是透明的,我們需要理解其工作機(jī)制,以防止內(nèi)存可見性問題,從而編寫出正確同步的代碼
    2021-06-06
  • Java獲取時(shí)間差(天數(shù)差,小時(shí)差,分鐘差)代碼示例

    Java獲取時(shí)間差(天數(shù)差,小時(shí)差,分鐘差)代碼示例

    這篇文章主要介紹了Java獲取時(shí)間差(天數(shù)差,小時(shí)差,分鐘差)代碼示例,使用SimpleDateFormat來實(shí)現(xiàn)的相關(guān)代碼,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-11-11
  • Java IO流 File類的常用API實(shí)例

    Java IO流 File類的常用API實(shí)例

    這篇文章主要介紹了Java IO流 File類的常用API實(shí)例的相關(guān)資料,需要的朋友參考下吧
    2017-05-05
  • java 中Map詳解及實(shí)例代碼

    java 中Map詳解及實(shí)例代碼

    這篇文章主要介紹了java 中Map詳解及實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下
    2017-04-04
  • MyBatis Plus復(fù)合主鍵問題的解決

    MyBatis Plus復(fù)合主鍵問題的解決

    在數(shù)據(jù)庫設(shè)計(jì)中,有時(shí)候需要使用復(fù)合主鍵來唯一標(biāo)識(shí)表中的一行數(shù)據(jù),本文將為您詳細(xì)介紹MyBatis Plus中復(fù)合主鍵的問題以及解決方案,具有一定的參考價(jià)值,感興趣的可以了解一下
    2023-09-09

最新評(píng)論

阜新市| 太保市| 利辛县| 虞城县| 深圳市| 克东县| 清新县| 阿瓦提县| 秦皇岛市| 隆安县| 苏尼特左旗| 克东县| 诏安县| 临湘市| 隆回县| 德兴市| 宁乡县| 汪清县| 山东| 赞皇县| 静安区| 保定市| 泸溪县| 屯昌县| 龙南县| 金华市| 普陀区| 民丰县| 镇巴县| 镇远县| 霞浦县| 沈丘县| 新野县| 唐海县| 唐河县| 敖汉旗| 镇江市| 白银市| 东莞市| 皋兰县| 平和县|