java使用SFTP上傳文件到資源服務(wù)器
本文實(shí)例為大家分享了java實(shí)現(xiàn)SFTP上傳文件到資源服務(wù)器工具類,供大家參考,具體內(nèi)容如下
首先得創(chuàng)建連接sftp服務(wù)器的公共類MySftp.java:
package cn.test.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpException; public class MySFTP { /** * 連接sftp服務(wù)器 * @param host 主機(jī) * @param port 端口 * @param username 用戶名 * @param password 密碼 */ public ChannelSftp connect(String host, int port, String username, String password) { ChannelSftp sftp = null; try { JSch jsch = new JSch(); jsch.getSession(username, host, port); Session sshSession = jsch.getSession(username, host, port); sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); Channel channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; } catch (Exception e) { } return sftp; } /** * 上傳文件 * * @param directory * 上傳的目錄 * @param uploadFile * 要上傳的文件 * @param sftp */ public void upload(String directory, String uploadFile, ChannelSftp sftp) { try { sftp.cd(directory); File file = new File(uploadFile); sftp.put(new FileInputStream(file), file.getName()); } catch (Exception e) { e.printStackTrace(); } } /** * 下載文件 * * @param directory * 下載目錄 * @param downloadFile * 下載的文件 * @param saveFile * 存在本地的路徑 * @param sftp */ public void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) { try { sftp.cd(directory); File file = new File(saveFile); sftp.get(downloadFile, new FileOutputStream(file)); } catch (Exception e) { e.printStackTrace(); } } /** * 刪除文件 * * @param directory * 要?jiǎng)h除文件所在目錄 * @param deleteFile * 要?jiǎng)h除的文件 * @param sftp */ public void delete(String directory, String deleteFile, ChannelSftp sftp) { try { sftp.cd(directory); sftp.rm(deleteFile); } catch (Exception e) { e.printStackTrace(); } } public void uploadSFTP(HttpServletRequest request,String[] uploadFiles) throws Exception { MySFTP mySFTP = new MySFTP(); SFTPUtil sFTPUtil =new SFTPUtil(); ChannelSftp sftp = null; Session session = null; try { sftp = mySFTP.connect(SystemConstants.SFTP_host, Integer.parseInt(SystemConstants.SFTP_port), SystemConstants.SFTP_username, SystemConstants.SFTP_password); for (int i = 0; i < uploadFiles.length; i++) { Date uploadTime = new Date(); String url=request.getSession().getServletContext().getRealPath("").replaceAll("\\\\", "/"); String uploadFile =url.substring(0, url.lastIndexOf("/"))+uploadFiles[i]; // String saveFile=""; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String ymd = sdf.format(uploadTime); String relativePath = ymd + "/"; String directory = SystemConstants.SFTP_directory+ relativePath; sFTPUtil.createDir(directory, sftp); mySFTP.upload(directory, uploadFile, sftp); sftp.cd(directory); } } catch (Exception e) { e.printStackTrace(); }finally{ try { if(sftp != null) { sftp.disconnect(); } } catch (Exception e) { e.printStackTrace(); } try { if(session != null) { session.disconnect(); } } catch (Exception e) { e.printStackTrace(); } } } /** * 列出目錄下的文件 * * @param directory * 要列出的目錄 * @param sftp * @return * @throws SftpException */ @SuppressWarnings("rawtypes") public Vector listFiles(String directory, ChannelSftp sftp) throws SftpException { return sftp.ls(directory); } }
上傳圖片時(shí),調(diào)用SFTPUtil類中的uploadMultipartFile方法即可。
package cn.test.util; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import org.springframework.web.multipart.MultipartFile; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpATTRS; import com.jcraft.jsch.SftpException; /**文件上傳工具類*/ public class SFTPUtil { /** * spring文件上傳方法 * */ public static String uploadMultipartFile(MultipartFile file,String fileExt) { SFTPUtil sFTPUtil =new SFTPUtil(); String originalFilename = file.getOriginalFilename(); //生成文件名 Date uploadTime = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String ymd = sdf.format(uploadTime); String relativePath = ymd+"/"; SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String fileName = df.format(uploadTime) + "_" + new Random().nextInt(1000) + "." + fileExt; // String fileName = String.valueOf(new Date().getTime())+ new Random().nextInt(10000)+"."+originalFilename.substring(originalFilename.lastIndexOf(".") + 1); String directory=SystemConstants.SFTP_directory+relativePath; ChannelSftp sftp =null; Session session = null; try { MySFTP mySFTP = new MySFTP(); sftp = mySFTP.connect(SystemConstants.SFTP_host, Integer.parseInt(SystemConstants.SFTP_port), SystemConstants.SFTP_username, SystemConstants.SFTP_password); session = sftp.getSession(); sFTPUtil.createDir(directory, sftp); sftp.cd(directory); sftp.put(file.getInputStream(), fileName); sftp.disconnect(); sftp.getSession().disconnect(); } catch (Exception e) { System.out.println("文件[" + originalFilename + "]上傳失敗,堆棧軌跡如下:"); e.printStackTrace(); }finally{ try { if(sftp != null) { sftp.disconnect(); } } catch (Exception e) { e.printStackTrace(); } try { if(session != null) { session.disconnect(); } } catch (Exception e) { e.printStackTrace(); } } String reName=SystemConstants.SFTP_httpBaseUrl+relativePath+fileName; return reName; } /** * 創(chuàng)建目錄 * @throws Exception */ public void createDir(String createpath, ChannelSftp sftp) throws Exception { try { if (isDirExist(sftp, createpath)) { sftp.cd(createpath); } String pathArry[] = createpath.split("/"); StringBuffer filePath = new StringBuffer("/"); for (String path : pathArry) { if (path.equals("")) { continue; } filePath.append(path + "/"); if (isDirExist(sftp, filePath.toString())) { sftp.cd(filePath.toString()); } else { // 建立目錄 sftp.mkdir(filePath.toString()); // 進(jìn)入并設(shè)置為當(dāng)前目錄 sftp.cd(filePath.toString()); } } sftp.cd(createpath); } catch (SftpException e) { throw new Exception(e.getMessage()); } } /** * 判斷目錄是否存在 */ public boolean isDirExist(ChannelSftp sftp,String directory) { boolean isDirExistFlag = false; try { SftpATTRS sftpATTRS = sftp.lstat(directory); isDirExistFlag = true; return sftpATTRS.isDir(); } catch (Exception e) { if (e.getMessage().toLowerCase().equals("no such file")) { isDirExistFlag = false; } } return isDirExistFlag; } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解決maven update project 后項(xiàng)目jdk變成1.5的問題
下面小編就為大家?guī)硪黄鉀Qmaven update project 后項(xiàng)目jdk變成1.5的問題。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起 小編過來看看吧2016-11-11springboot實(shí)現(xiàn)訪問多個(gè)redis庫(kù)
這篇文章主要介紹了springboot實(shí)現(xiàn)訪問多個(gè)redis庫(kù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05Mybatis-plus使用TableNameHandler分表詳解(附完整示例源碼)
這篇文章主要介紹了Mybatis-plus使用TableNameHandler分表詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01maven無法自動(dòng)導(dǎo)入依賴jar包解決方式
有時(shí)候Maven無法自動(dòng)導(dǎo)入包是因?yàn)樵摪聪螺d到本地倉(cāng)庫(kù)中,本文就來介紹一下解決方法,具有一定的參考價(jià)值,感興趣的可以了解一下2024-08-08jedis連接池對(duì)commons-pool的封裝示例詳解
這篇文章主要為大家介紹了jedis連接池對(duì)commons-pool的封裝示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09在CentOS系統(tǒng)上安裝Java的openjdk的方法
這篇文章主要介紹了在CentOS系統(tǒng)上安裝Java的openjdk的方法,同樣適用于Fedora等其他RedHat系的Linux系統(tǒng),需要的朋友可以參考下2015-06-06Java修改圖片大小尺寸的簡(jiǎn)單實(shí)現(xiàn)
這篇文章主要介紹了Java修改圖片大小尺寸的簡(jiǎn)單實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09java基礎(chǔ)之初始化ArrayList時(shí)直接賦值的4種方式總結(jié)
ArrayList是Java中的一個(gè)類,它是Java集合框架中的一部分,用于實(shí)現(xiàn)動(dòng)態(tài)數(shù)組,下面這篇文章主要給大家介紹了關(guān)于java基礎(chǔ)之初始化ArrayList時(shí)直接賦值的4種方式,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-07-07