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

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

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

瀏覽:42日期: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
相關文章:
主站蜘蛛池模板: 学习虾-免费的学习资料下载平台| jrs高清nba(无插件)直播-jrs直播低调看直播-jrs直播nba-jrs直播 上海地磅秤|电子地上衡|防爆地磅_上海地磅秤厂家–越衡称重 | 伺服电机维修、驱动器维修「安川|三菱|松下」伺服维修公司-深圳华创益 | 科昊仪器超纯水机系统-可成气相液氮罐-美菱超低温冰箱-西安昊兴生物科技有限公司 | 送料机_高速冲床送料机_NC伺服滚轮送料机厂家-东莞市久谐自动化设备有限公司 | 天津暖气片厂家_钢制散热器_天津铜铝复合暖气片_维尼罗散热器 | 传动滚筒,改向滚筒-淄博建凯机械科技有限公司 | 工业铝型材-铝合金电机壳-铝排-气动执行器-山东永恒能源集团有限公司 | 台湾阳明固态继电器-奥托尼克斯光电传感器-接近开关-温控器-光纤传感器-编码器一级代理商江苏用之宜电气 | 一体式钢筋扫描仪-楼板测厚仪-裂缝检测仪-泰仕特(北京) | 北京自然绿环境科技发展有限公司专业生产【洗车机_加油站洗车机-全自动洗车机】 | 聚氨酯保温钢管_聚氨酯直埋保温管道_聚氨酯发泡保温管厂家-沧州万荣防腐保温管道有限公司 | 飞飞影视_热门电影在线观看_影视大全| 铝合金重力铸造_铝合金翻砂铸造_铝铸件厂家-东莞市铝得旺五金制品有限公司 | 彩信群发_群发彩信软件_视频短信营销平台-达信通 | 穿线管|波纹穿线管|包塑金属软管|蛇皮管?闵彬专注弱电工程? | 南京兰江泵业有限公司-水解酸化池潜水搅拌机-絮凝反应池搅拌机-好氧区潜水推进器 | 菏泽商标注册_菏泽版权登记_商标申请代理_菏泽商标注册去哪里 | 颚式破碎机,圆锥破碎机,制砂机-新乡市德诚机电制造有限公司 | 合肥风管加工厂-安徽螺旋/不锈钢风管-通风管道加工厂家-安徽风之范 | 移动厕所租赁|移动卫生间|上海移动厕所租赁-家瑞租赁 | 外贮压-柜式-悬挂式-七氟丙烷-灭火器-灭火系统-药剂-价格-厂家-IG541-混合气体-贮压-非贮压-超细干粉-自动-灭火装置-气体灭火设备-探火管灭火厂家-东莞汇建消防科技有限公司 | 脑钠肽-白介素4|白介素8试剂盒-研域(上海)化学试剂有限公司 | 金环宇|金环宇电线|金环宇电缆|金环宇电线电缆|深圳市金环宇电线电缆有限公司|金环宇电缆集团 | 合肥花魁情感婚姻咨询中心_挽回爱情_修复婚姻_恋爱指南 | 今日娱乐圈——影视剧集_八卦娱乐_明星八卦_最新娱乐八卦新闻 | 钢制拖链生产厂家-全封闭钢制拖链-能源钢铝拖链-工程塑料拖链-河北汉洋机械制造有限公司 | 水平筛厂家-三轴椭圆水平振动筛-泥沙震动筛设备_山东奥凯诺矿机 包装设计公司,产品包装设计|包装制作,包装盒定制厂家-汇包装【官方网站】 | 罐体电伴热工程-消防管道电伴热带厂家-山东沃安电气 | 飞歌臭氧发生器厂家_水处理臭氧发生器_十大臭氧消毒机品牌 | 博医通医疗器械互联网供应链服务平台_博医通| 吹田功率计-长创耐压测试仪-深圳市新朗普电子科技有限公司 | VOC检测仪-甲醛检测仪-气体报警器-气体检测仪厂家-深恒安科技有限公司 | 全自动五线打端沾锡机,全自动裁线剥皮双头沾锡机,全自动尼龙扎带机-东莞市海文能机械设备有限公司 | 岩石钻裂机-液压凿岩机-劈裂机-挖改钻_湖南烈岩科技有限公司 | 选宝石船-陆地水上开采「精选」色选机械设备-青州冠诚重工机械有限公司 | 河南卓美创业科技有限公司-河南卓美防雷公司-防雷接地-防雷工程-重庆避雷针-避雷器-防雷检测-避雷带-避雷针-避雷塔、机房防雷、古建筑防雷等-山西防雷公司 | 破碎机锤头_耐磨锤头_合金锤头-鼎成机械一站式耐磨铸件定制服务 微型驱动系统解决方案-深圳市兆威机电股份有限公司 | 滚筒烘干机_转筒烘干机_滚筒干燥机_转筒干燥机_回转烘干机_回转干燥机-设备生产厂家 | 政府园区专业委托招商平台_助力企业选址项目快速落地_东方龙商务集团 | 美缝剂_美缝剂厂家_美缝剂加盟-地老板高端瓷砖美缝剂 |