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服务器 * @param host 主机 * @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 * 要删除文件所在目录 * @param deleteFile * 要删除的文件 * @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); } }
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; } /** * 创建目录 * @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()); // 进入并设置为当前目录 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; } }