1.項目環境
框架:springmvc
項目管理工具:maven
2.必須使用的jar
1 com.jcraft 2 jsch 3 0.1.27 4 test
3.新建一個FileUpDown工具類,在類中添加以下屬性
1 //linux服務器基本連接參數 2 String host = "";//ip 3 String username = "";//用戶名 4 String password = "";//密碼 5 int port = 22; 6 7 ChannelSftp sftp = null; 8 String remotePath = "/usr/java/file/img/";//服務器上的目標路徑 9 String path;//實際路徑
以上屬性可以定義為private,可將相關屬性值寫入*.properties文件,然后讀取.
4.連接服務器並獲得ChannelSftp
1 //連接服務器 獲得ChannelSftp 2 public ChannelSftp getSftp() { 3 try { 4 JSch jsch = new JSch(); 5 Session session = jsch.getSession(username, host, port); 6 session.setPassword(password); 7 Properties properties = new Properties(); 8 properties.put("StrictHostKeyChecking", "no"); 9 session.setConfig(properties); 10 session.connect(); 11 Channel channel = session.openChannel("sftp"); 12 channel.connect(); 13 sftp = (ChannelSftp) channel; 14 System.out.println("連接成功"); 15 } catch (Exception e) { 16 System.out.println("連接失敗"); 17 e.printStackTrace(); 18 } 19 return sftp; 20 }
5.上傳文件
1 //上傳文件 2 public String upLoad(MultipartFile file){ 3 ... 4 }
現在上傳的是單個文件,如果上傳多個文件時可傳入List,MultipartFile是spring提供的類型.
在方法中寫上以下代碼:
1 //上傳文件 2 public String upLoad(MultipartFile file) throws IOException, SftpException { 3 InputStream is =null; 4 try{ 5 //要上傳的文件名 6 String filename = file.getOriginalFilename(); 7 String suffix = filename.substring(filename.lastIndexOf(".")); 8 //自動生成文件名 9 String autofilename = UUID.randomUUID().toString(); 10 //生成路徑加文件名 11 String path = remotePath + autofilename + suffix; 12 //得到文件輸入流 13 is = file.getInputStream(); 14 this.getSftp().put(is, path); 15 }finally { 16 //1.關閉輸入流 17 //2.斷開連接 18 ... 19 } 20 return path; 21 }
6.斷開服務
1 public void close() { 2 if (this.sftp != null) { 3 if (this.sftp.isConnected()) { 4 this.sftp.disconnect(); 5 } else if (this.sftp.isClosed()) { 6 System.out.println("斷開服務成功"); 7 } 8 } 9 }