javaweb上传文件到服务器中
2017-03-07 10:46
337 查看
项目中经常要做上传功能,除了页面使用上传组件外,后台的文件处理一种是 存放在项目中文件夹,另一种存放部署的服务器中,后一种更灵活对项目更友好。
JSch是Java Secure Channel的缩写。JSch是一个SSH2的纯Java实现。它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,当然你也可以集成它的功能到你自己的应用程序。
本文只介绍如何使用JSch实现的SFTP功能。
SFTP是Secure File Transfer Protocol的缩写,安全文件传送协议。可以为传输文件提供一种安全的加密方法。SFTP 为 SSH的一部份,是一种传输文件到服务器的安全方式。SFTP是使用加密传输认证信息和传输的数据,所以,使用SFTP是非常安全的。但是,由于这种传输方式使用了加密/解密技术,所以传输效率比普通的FTP要低得多,如果您对网络安全性要求更高时,可以使用SFTP代替FTP。(来自百度的解释)
要使用JSch,需要下载它的jar包,请从官网下载它:http://www.jcraft.com/jsch/
ChannelSftp类是JSch实现SFTP核心类,它包含了所有SFTP的方法,如:
put(): 文件上传
get(): 文件下载
cd(): 进入指定目录
ls(): 得到指定目录下的文件列表
rename(): 重命名指定文件或目录
rm(): 删除指定文件
mkdir(): 创建目录
rmdir(): 删除目录
以下是stfpUtils工具类的方法
JSch是Java Secure Channel的缩写。JSch是一个SSH2的纯Java实现。它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,当然你也可以集成它的功能到你自己的应用程序。
本文只介绍如何使用JSch实现的SFTP功能。
SFTP是Secure File Transfer Protocol的缩写,安全文件传送协议。可以为传输文件提供一种安全的加密方法。SFTP 为 SSH的一部份,是一种传输文件到服务器的安全方式。SFTP是使用加密传输认证信息和传输的数据,所以,使用SFTP是非常安全的。但是,由于这种传输方式使用了加密/解密技术,所以传输效率比普通的FTP要低得多,如果您对网络安全性要求更高时,可以使用SFTP代替FTP。(来自百度的解释)
要使用JSch,需要下载它的jar包,请从官网下载它:http://www.jcraft.com/jsch/
ChannelSftp类是JSch实现SFTP核心类,它包含了所有SFTP的方法,如:
put(): 文件上传
get(): 文件下载
cd(): 进入指定目录
ls(): 得到指定目录下的文件列表
rename(): 重命名指定文件或目录
rm(): 删除指定文件
mkdir(): 创建目录
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服务器 * @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服务器 * @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(); //设置密钥和密码 if (!StringUtils.isEmpty(privateKey)) { if (!StringUtils.isEmpty(passphrase)) { //设置带口令的密钥 jsch.addIdentity(privateKey, passphrase); } else { //设置不带口令的密钥 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 downloadFil aa2a e, 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协议连接。
相关文章推荐
- Javaweb上传图片或文件到服务器,Tomcat服务器重新部署项目,会删除原来上传的文件的问题
- java web-上传文件到tomcat服务器上路径问题
- Java Web 学习笔记之一:服务器获取表单上传的文件
- Java客户端通过Http发送POST请求上传文件到web服务器
- Java客户端通过Http发送POST请求上传文件到web服务器
- java web FTPClient 实现上传文件到指定服务器
- JAVA实现FTP服务器文件的上传,下载,删除功能
- 文件上传到Web服务器
- 【转】WinFrom通过WebClient向Web服务器上传下载文件(带进度条)
- asp.net使用FtpWebRequest向ftp上传文件报错 基础连接已经关闭: 服务器提交了协议冲突
- Java 服务器多线程处理文件上传
- WinFrom通过WebClient向Web服务器上传下载文件(带进度条)
- WinFrom通过WebClient向Web服务器上传下载文件
- java 的 web 服务器 jswdk 的配置文件 webserver.xml
- goAhead上实现文件上传到嵌入式web服务器上
- [置顶] Android上传文件到Web服务器,PHP接收文件(一)
- 用HttpListener做web服务器,简单解析post方式过来的参数、上传的文件
- 使用WinInet向 ASP.Net Web服务器 多线程上传文件
- JAVA应用XFire框架来实现WebServie的大文件传输功能之二(上传)
- java web 利用 commons-fileupload-1.2 实现文件上传 解决 中文乱码& 非文件属性的读取