亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

Java如何實現上傳文件到服務器指定目錄

瀏覽:7日期:2022-09-02 17:09:06

前言需求

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

具體實現

引入的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

@Configurationpublic 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('遠程服務器新建文件名不能為空!'); } 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連接服務器失敗'); } 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上傳文件至服務器出錯'+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連接服務器失敗'+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()); // 進入并設置為當前目錄 channelSftp.cd(filePath.toString()); }} catch (SftpException e) { e.printStackTrace(); throw new JSchException('SFTP無法正常操作服務器'+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容器。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Java
相關文章:
主站蜘蛛池模板: 免费的全黄一级录像带 | 日韩激情淫片免费看 | 亚洲第一区精品日韩在线播放 | 亚洲欧美视频二区 | 成人亚洲国产综合精品91 | 国产亚洲欧美久久久久 | 婷婷精品视频 | 亚洲日本中文字幕一本 | 免费一级毛片在线播放傲雪网 | 中国china体内裑精亚洲毛片 | 污视频在线观看免费 | 国产短视频在线 | 黄网免费 | 黄色网络免费 | 黄色毛片小视频 | 免费观看欧美成人禁片 | 一级在线视频 | 国产床上视频 | 澳门久久 | 黄短视频在线观看免费版 | 成年人的黄色 | 国产成在线观看免费视频 | 欧美色欧美亚洲另类二区 | www.毛片在线观看 | 99视频精品全部免费免费观 | 国产精品第一页第一页 | 国产人碰人摸人爱视频 | 国产在线主播 | 国产亚洲欧美日韩国产片 | 日本一级毛一级毛片短视频 | 久久免费福利视频 | 一级香蕉免费毛片 | 99视频在线精品 | 视色4se影院在线播放 | 午夜影视污 | wwwxxx亚洲| 免费视频成人国产精品网站 | 伊人热人久久中文字幕 | 青青草免费观看 | 国产国语在线播放视频 | 一级不卡毛片免费 |