国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

javaweb上傳文件到服務(wù)器中

2019-11-06 06:16:02
字體:
供稿:網(wǎng)友

   項目中經(jīng)常要做上傳功能,除了頁面使用上傳組件外,后臺的文件處理一種是 存放在項目中文件夾,另一種存放部署的服務(wù)器中,后一種更靈活對項目更友好。

JSch是java Secure Channel的縮寫。JSch是一個SSH2的純Java實現(xiàn)。它允許你連接到一個SSH服務(wù)器,并且可以使用端口轉(zhuǎn)發(fā),X11轉(zhuǎn)發(fā),文件傳輸?shù)?,?dāng)然你也可以集成它的功能到你自己的應(yīng)用程序。  本文只介紹如何使用JSch實現(xiàn)的SFTP功能。  SFTP是Secure File Transfer PRotocol的縮寫,安全文件傳送協(xié)議??梢詾閭鬏斘募峁┮环N安全的加密方法。SFTP 為 SSH的一部份,是一種傳輸文件到服務(wù)器的安全方式。SFTP是使用加密傳輸認(rèn)證信息和傳輸?shù)臄?shù)據(jù),所以,使用SFTP是非常安全的。但是,由于這種傳輸方式使用了加密/解密技術(shù),所以傳輸效率比普通的FTP要低得多,如果您對網(wǎng)絡(luò)安全性要求更高時,可以使用SFTP代替FTP。(來自百度的解釋)   要使用JSch,需要下載它的jar包,請從官網(wǎng)下載它:http://www.jcraft.com/jsch/ ChannelSftp類是JSch實現(xiàn)SFTP核心類,它包含了所有SFTP的方法,如:put():      文件上傳get():      文件下載cd():       進(jìn)入指定目錄ls():       得到指定目錄下的文件列表rename():   重命名指定文件或目錄rm():       刪除指定文件mkdir():    創(chuàng)建目錄rmdir():    刪除目錄以下是stfpUtils工具類的方法
package com.pzedu.infrastructure.common.util;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.util.Properties;import java.util.Vector;import org.apache.commons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.jcraft.jsch.Channel;import com.jcraft.jsch.ChannelSftp;import com.jcraft.jsch.ChannelSftp.LsEntry;import com.jcraft.jsch.JSch;import com.jcraft.jsch.session;import com.jcraft.jsch.SftpException;/** * sftp 工具類 *  * @author weird */public final class Sftps {	private static final Logger log = LoggerFactory.getLogger(Sftps.class);		private Session sshSession;		private ChannelSftp sftp;		/**	 * 連接sftp服務(wù)器	 * @param host	 * @param port	 * @param username	 * @param passWord	 * @return	 * @throws Exception	 */	public ChannelSftp connect(String host, int port, String username, String password) throws Exception {		JSch jsch = new JSch();		sshSession = jsch.getSession(username, host, port);				log.debug("Session created.");				sshSession.setPassword(password);		Properties sshConfig = new Properties();		sshConfig.put("StrictHostKeyChecking", "no");		sshSession.setConfig(sshConfig);		sshSession.connect();				log.debug("Session connected.");		log.debug("Opening Channel.");				Channel channel = sshSession.openChannel("sftp");		channel.connect();		sftp = (ChannelSftp) channel;				log.debug("Connected to " + host + ".");				return sftp;	}	/**	 * 連接sftp服務(wù)器	 * @param host	 * @param port	 * @param username	 * @param privateKey	 * @param passphrase	 * @return	 * @throws Exception 	 */	public ChannelSftp connect(String host, int port, String username, String privateKey ,String passphrase) throws Exception {		JSch jsch = new JSch();				//設(shè)置密鑰和密碼	    if (!StringUtils.isEmpty(privateKey)) {	        if (!StringUtils.isEmpty(passphrase)) {	            //設(shè)置帶口令的密鑰	            jsch.addIdentity(privateKey, passphrase);	        } else {	            //設(shè)置不帶口令的密鑰	            jsch.addIdentity(privateKey);	        }	    }		sshSession = jsch.getSession(username, host, port);				log.debug("Session created.");				Properties sshConfig = new Properties();		sshConfig.put("StrictHostKeyChecking", "no");		sshSession.setConfig(sshConfig);		sshSession.connect();				log.debug("Session connected.");		log.debug("Opening Channel.");				Channel channel = sshSession.openChannel("sftp");		channel.connect();		sftp = (ChannelSftp) channel;				log.debug("Connected to " + host + ".");				return sftp;	}		public void portForwardingL(int lport, String rhost, int rport) throws Exception {		int assinged_port = sshSession.setPortForwardingL(lport, rhost, rport);	    System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);	}	/**	 * 斷開連接	 */	public void disconnect() {		if (sftp != null) sftp.disconnect();		if (sshSession != null) sshSession.disconnect();	}	/**	 * 上傳文件	 * 	 * @param directory	 *            上傳的目錄	 * @param uploadFile	 *            要上傳的文件	 * @param sftp	 */	public void upload(String directory, String uploadFile) throws Exception {		sftp.cd(directory);		File file = new File(uploadFile);		sftp.put(new FileInputStream(file), file.getName());	}		public void upload(String directory, File file) throws Exception {		sftp.cd(directory);		sftp.put(new FileInputStream(file), file.getName());		System.out.println("upload file "+file.getAbsolutePath() + " to host " + sshSession.getHost());	}		public void uploadDir(File src, String dst) throws Exception {		if (!exist(dst)) {			sftp.mkdir(dst);		}		if (src.isFile()) {			upload(dst, src);		} else {			for (File file : src.listFiles()) {				if (file.isDirectory()) {					uploadDir(file, dst + "/" + file.getName());				}				upload(dst, file);			}		}	}	/**	 * 目錄是否查找	 * @param path	 * @return	 * @throws SftpException	 */	public boolean exist(String path) throws SftpException {		String pwd = sftp.pwd();		try {			sftp.cd(path);		} catch (SftpException e) {			if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {				return false;			} else {				throw e;			}		} finally {			sftp.cd(pwd);		}				return true;	}	/**	 * 下載文件	 * @param directory	 * @param downloadFile	 * @param saveFile	 * @throws Exception	 */	public void download(String directory, String downloadFile, String saveFile) throws Exception {		sftp.cd(directory);		File file = new File(saveFile);		sftp.get(downloadFile, new FileOutputStream(file));	}		/**	 * 下載文件	 * @param directory	 * @param downloadFile	 * @param saveFile	 * @throws Exception	 */	public void download(String directory, String downloadFile, File saveFile) throws Exception {		sftp.cd(directory);		sftp.get(downloadFile, new FileOutputStream(saveFile));		System.out.println("download file "+directory + "/" +downloadFile + " from host " + sshSession.getHost());	}		/**	 * 下載文件	 * @param src	 * @param dst	 * @throws Exception	 */	@SuppressWarnings("unchecked")	public void downloadDir(String src, File dst) throws Exception {		try {			sftp.cd(src);		} catch (Exception e) {			// TODO Auto-generated catch block			e.printStackTrace();		}				dst.mkdirs();				Vector<LsEntry> files = sftp.ls(src);		for (LsEntry lsEntry : files) {			if (lsEntry.getFilename().equals(".") || lsEntry.getFilename().equals("..")) {				continue;			}			if (lsEntry.getLongname().startsWith("d")) {				downloadDir(src + "/" + lsEntry.getFilename(), new File(dst, lsEntry.getFilename()));			} else {				download(src, lsEntry.getFilename(), new File(dst, lsEntry.getFilename()));			}					}	}	/**	 *  刪除文件	 * @param directory	 * @param deleteFile	 * @throws SftpException	 */	public void delete(String directory, String deleteFile) throws SftpException {		sftp.cd(directory);		sftp.rm(deleteFile);	}	/**	 * 列出目錄下的文件	 * @param directory	 * @return	 * @throws SftpException	 */	public Vector listFiles(String directory) throws SftpException {		return sftp.ls(directory);	}	public static void main(String[] args) throws Exception {		Sftps sf = new Sftps();		String host = "192.168.56.101";		int port = 22;		String username = "root";		String password = "123";		String privateKey = "C:/Users/Administrator/Desktop/seRT_SSH_key/front/Identity";		String passphrase = "h$VgBrx3nhwH#2!h6zs0uGhzcCX8dTPa";		String src = "/usr/local/apache-tomcat-7.0.63/webapps/pzedu";				sf.connect(host, port, username, privateKey, passphrase);		sf.portForwardingL(1194, "10.169.97.248", 1194);		//		ChannelSftp sftp = sf.connect(host, port, username, password);//		sf.upload(directory, uploadFile, sftp);//		sf.download(directory, downloadFile, saveFile, sftp);//		sf.delete(directory, deleteFile, sftp);				//		try {////			Vector files = sf.listFiles("/root");//			sf.downloadDir(src, new File("C:/staticsfile"));////			sf.uploadDir(new File("C:/staticsfile"), "/root/temp");//			System.out.println("finished");//			sftp.disconnect();//		} catch (Exception e) {//			e.printStackTrace();//		}//		sf.disconnect();	}		public Session getSshSession() {		return sshSession;	}	public ChannelSftp getSftp() {		return sftp;	}}采用的是stfp協(xié)議連接。


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 富顺县| 杭锦旗| 祁连县| 屯门区| 辉南县| 永修县| 丰城市| 临漳县| 太和县| 波密县| 孝义市| 溧阳市| 油尖旺区| 桦南县| 富源县| 连州市| 沽源县| 迭部县| 甘孜县| 大方县| 黄山市| 循化| 蓬莱市| 辽阳市| 乌苏市| 舞钢市| 昌黎县| 浦东新区| 靖边县| 衡水市| 临清市| 防城港市| 无极县| 容城县| 桂东县| 宁德市| 宕昌县| 南皮县| 循化| 义马市| 临夏市|