电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

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

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

瀏覽:43日期: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
相關文章:
主站蜘蛛池模板: 外贸资讯网 - 洞悉全球贸易,把握市场先机 | 光栅尺_Magnescale探规_磁栅尺_笔式位移传感器_苏州德美达 | 热熔胶网膜|pes热熔网膜价格|eva热熔胶膜|热熔胶膜|tpu热熔胶膜厂家-苏州惠洋胶粘制品有限公司 | 数控专用机床,专用机床,自动线,组合机床,动力头,自动化加工生产线,江苏海鑫机床有限公司 | 一体化污水处理设备,一体化污水设备厂家-宜兴市福源水处理设备有限公司 | 二维运动混料机,加热型混料机,干粉混料机-南京腾阳干燥设备厂 | 品牌设计_VI设计_电影海报设计_包装设计_LOGO设计-Bacross新越品牌顾问 | 传动滚筒_厂家-淄博海恒机械制造厂 | 注浆压力变送器-高温熔体传感器-矿用压力传感器|ZHYQ朝辉 | 精密线材测试仪-电线电缆检测仪-苏州欣硕电子科技有限公司 | 智慧水务|智慧供排水利信息化|水厂软硬件系统-上海敢创 | 远程会诊系统-手术示教系统【林之硕】医院远程医疗平台 | 电动葫芦|防爆钢丝绳电动葫芦|手拉葫芦-保定大力起重葫芦有限公司 | 贵州自考_贵州自学考试网| 网站建设-网站制作-网站设计-网站开发定制公司-网站SEO优化推广-咏熠软件 | 浙江筋膜枪-按摩仪厂家-制造商-肩颈按摩仪哪家好-温州市合喜电子科技有限公司 | 砍排机-锯骨机-冻肉切丁机-熟肉切片机-预制菜生产线一站式服务厂商 - 广州市祥九瑞盈机械设备有限公司 | 海鲜池-专注海鲜鱼缸、移动海鲜缸、饭店鱼缸设计定做-日晟水族厂家 | MVE振动电机_MVE震动电机_MVE卧式振打电机-河南新乡德诚生产厂家 | 精雕机-火花机-精雕机 cnc-高速精雕机-电火花机-广东鼎拓机械科技有限公司 | 震动筛选机|震动分筛机|筛粉机|振筛机|振荡筛-振动筛分设备专业生产厂家高服机械 | 岛津二手液相色谱仪,岛津10A液相,安捷伦二手液相,安捷伦1100液相-杭州森尼欧科学仪器有限公司 | 河南不锈钢水箱_地埋水箱_镀锌板水箱_消防水箱厂家-河南联固供水设备有限公司 | 扒渣机,铁水扒渣机,钢水扒渣机,铁水捞渣机,钢水捞渣机-烟台盛利达工程技术有限公司 | 渣油泵,KCB齿轮泵,不锈钢齿轮泵,重油泵,煤焦油泵,泊头市泰邦泵阀制造有限公司 | 海外整合营销-独立站营销-社交媒体运营_广州甲壳虫跨境网络服务 焊管生产线_焊管机组_轧辊模具_焊管设备_焊管设备厂家_石家庄翔昱机械 | 防爆电机-高压防爆电机-ybx4电动机厂家-河南省南洋防爆电机有限公司 | 聚合氯化铝-碱式氯化铝-聚合硫酸铁-聚氯化铝铁生产厂家多少钱一吨-聚丙烯酰胺价格_河南浩博净水材料有限公司 | 数控走心机-双主轴走心机厂家-南京建克 | 活性炭-蜂窝-椰壳-柱状-粉状活性炭-河南唐达净水材料有限公司 | 中山东港家具集团-酒店-办公-医养家具定制厂家 | 精密钢管,冷拔精密无缝钢管,精密钢管厂,精密钢管制造厂家,精密钢管生产厂家,山东精密钢管厂家 | 蒸汽热收缩机_蒸汽发生器_塑封机_包膜机_封切收缩机_热收缩包装机_真空机_全自动打包机_捆扎机_封箱机-东莞市中堡智能科技有限公司 | 压砖机_电动螺旋压力机_粉末成型压力机_郑州华隆机械tel_0371-60121717 | 液晶拼接屏厂家_拼接屏品牌_拼接屏价格_监控大屏—北京维康 | 重庆网站建设,重庆网站设计,重庆网站制作,重庆seo,重庆做网站,重庆seo,重庆公众号运营,重庆小程序开发 | 无缝钢管-聊城无缝钢管-小口径无缝钢管-大口径无缝钢管 - 聊城宽达钢管有限公司 | 混合生育酚_醋酸生育酚粉_琥珀酸生育酚-山东新元素生物科技 | 好杂志网-首页| 聚合甘油__盐城市飞龙油脂有限公司 | 十二星座查询(性格特点分析、星座运势解读) - 玄米星座网 |