Java如何實現(xiàn)上傳文件到服務(wù)器指定目錄
前言需求
使用freemarker生成的靜態(tài)文件,統(tǒng)一存儲在某個服務(wù)器上。本來一開始打算使用ftp實現(xiàn)的,奈何老連接不上,改用jsch。畢竟有現(xiàn)成的就很舒服,在此介紹給大家。
具體實現(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>
建立實體類
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("遠程服務(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ù)器出錯"+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()); // 進入并設(shè)置為當前目錄 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)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Spring中@RabbitHandler和@RabbitListener的區(qū)別詳析
@RabbitHandler是用于處理消息的方法注解,它與@RabbitListener注解一起使用,這篇文章主要給大家介紹了關(guān)于Spring中@RabbitHandler和@RabbitListener區(qū)別的相關(guān)資料,需要的朋友可以參考下2024-02-02Java應(yīng)用啟動停止重啟Shell腳本模板server.sh
這篇文章主要為大家介紹了Java應(yīng)用啟動、停止、重啟Shell腳本模板server.sh,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08MyBatis-Plus實現(xiàn)對查詢結(jié)果進行分頁的基本步驟
MyBatis-Plus 是一個 MyBatis 的增強工具,在 MyBatis 的基礎(chǔ)上只做增強不做改變,為簡化開發(fā)、提高效率而生,MyBatis-Plus 支持多種數(shù)據(jù)庫的分頁查詢,其分頁功能是通過 Page 類實現(xiàn)的,本文介紹了使用 MyBatis-Plus 實現(xiàn)分頁查詢的基本步驟,需要的朋友可以參考下2024-08-08Spring MVC Mybatis多數(shù)據(jù)源的使用實例解析
項目需要從其他網(wǎng)站獲取數(shù)據(jù),因為是臨時加的需求,這篇文章主要介紹了Spring MVC Mybatis多數(shù)據(jù)源的使用實例解析,需要的朋友可以參考下2016-12-12Java的外部類為什么不能使用private和protected進行修飾的講解
今天小編就為大家分享一篇關(guān)于Java的外部類為什么不能使用private和protected進行修飾的講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-04-04MyBatis的JdbcType與Oracle、MySql數(shù)據(jù)類型一覽表
這篇文章主要介紹了MyBatis的JdbcType與Oracle、MySql數(shù)據(jù)類型一覽表,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01詳解Idea 2019.2 安裝lombok插件失效問題解決
這篇文章主要介紹了詳解Idea 2019.2 安裝lombok插件失效問題解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-10-10