sftp文件上传和下载
下面是java 代码sftp文件上传和下载具体实现
1.连接服务器类
package Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
/*
* @author lixiongjun
*
* 利用JSch包实现创建ChannelSftp通信对象的工具类
* 2015-1-27 上午10:03:21
*/
public class SftpUtil {
private static String ip = null; // ip 主机IP
private static int port = -1; // port 主机ssh2登陆端口,如果取默认值,传-1 private static String user = null; // user 主机登陆用户名
private static String psw = null; // psw 主机登陆密码
private static String servicePath = null; // 服务存储文件路径 private static Properties prop = null; private static Session session = null;
private static Channel channel = null; // 读取配置文件的参数 static { prop = new Properties(); ClassLoader cl = SftpUtil.class.getClassLoader(); InputStream is = cl .getResourceAsStream("Test/Sftp_UpDownload.properties"); try {
prop.load(is); } catch (IOException e) {
// System.out.println("读取配置文件出错!"); e.printStackTrace(); } ip = prop.getProperty("ip"); port = Integer.parseInt(prop.getProperty("port"));
user = prop.getProperty("user"); psw = prop.getProperty("psw");
servicePath = prop.getProperty("servicePath");
} /**
* 获取 sftp通信 * * @return 获取到的ChannelSftp
* @throws Exception
*/
public static ChannelSftp getSftp() throws Exception { ChannelSftp sftp = null;
JSch jsch = new JSch();
if (port <= 0) {
// 连接服务器,采用默认端口
session = jsch.getSession(user, ip);
} else {
// 采用指定的端口连接服务器
session = jsch.getSession(user, ip, port); }
// 如果服务器连接不上,则抛出异常
if (session == null) {
throw new Exception("session is null"); }
// 设置登陆主机的密码
session.setPassword(psw);// 设置密码
// 设置第一次登陆的时候提示,可选值:(ask | yes | no) session.setConfig("StrictHostKeyChecking", "no"); // 设置登陆超时时间 session.connect(30000);
try { // 创建sftp通信通道 channel = (Channel) session.openChannel("sftp"); channel.connect();
sftp = (ChannelSftp) channel;
// 进入服务器指定的文件夹
sftp.cd(servicePath); } catch (Exception e) { e.printStackTrace(); } return sftp; } /**
* 关闭连接 */ public static void closeSftp() {
if (channel != null) { if (channel.isConnected())
channel.disconnect();
}
if (session != null) {
if (session.isConnected())
session.disconnect();
}
}
}
2.上传下载工具类
package Test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader;
import java.io.OutputStream;
import org.junit.Test;
import com.jcraft.jsch.ChannelSftp;
public class SftpUploadOrDownload { /*
* @author lixiongjun *
* 实现sftp文件上传下载的工具类
* 2015-1-27 下午15:13:26
*/
/**
* 上传本地文件到服务器
* @param srcPath 本地文件路径
* @param dstFilename 目标文件名
* @return 是否上传成功 */ public boolean upload(String srcPath,String dstFilename){ ChannelSftp sftp=null;
try {
sftp =SftpUtil.getSftp();
sftp.put(srcPath,dstFilename);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
finally{ SftpUtil.closeSftp(); }
}
/**
* 上传本地文件到服务器
* @param in 输入流
* @param dstFilename 目标文件名
* @return 是否上传成功 */ public boolean uploadBystrem(InputStream in,String dstFilename){ ChannelSftp sftp=null; try { sftp =SftpUtil.getSftp(); sftp.put(in,dstFilename);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
finally{
SftpUtil.closeSftp();
}
}
/**
* 把服务器文件下载到本地
* @param desPath 下载到本地的目标路径
* @param srcFilename 源文件名
* @return 是否下载成功 */ public boolean download(String srcFilename,String dstPath){ ChannelSftp sftp=null;
try {
sftp =SftpUtil.getSftp();
sftp.get(srcFilename,dstPath);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
finally{ SftpUtil.closeSftp(); }
} /**
* 获取服务器文件的内容,只对文本文件有效 * @param srcFilename 服务器所在源文件名
* @return 文件内容 */ public String getServiceFileContext(String srcFilename){ ChannelSftp sftp=null; InputStream in=null; BufferedReader br=null; String filecontext=""; try { sftp =SftpUtil.getSftp();
in=sftp.get(srcFilename); br=new BufferedReader(new InputStreamReader(in)); String str=br.readLine(); while(str!=null){ filecontext+=str+"\n"; str=br.readLine(); } } catch (Exception e) { e.printStackTrace(); } finally{ try {
br.close(); in.close(); } catch (IOException e) {
e.printStackTrace();
}
SftpUtil.closeSftp();
}
return filecontext;
}
/**
* 删除服务器上文件
* @param filename 要删除的文件名
* @return 是否删除成功
*/
public boolean remove(String filename){ ChannelSftp sftp=null; try { sftp =SftpUtil.getSftp(); sftp.rm(filename); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally{ SftpUtil.closeSftp(); }
} @Test
public void TestSftpUpload(){ if(upload("E:/test.txt","test.txt")){
System.out.println("上传文件成功");
} else{
System.out.println("上传文件失败"); } }
@Test
public void TestSftpDownload(){ if(download("test.txt","E:/downtest.txt")){ System.out.println("下载文件成功");
} else{
System.out.println("下载文件失败"); } }
@Test public void TestSftpgetServiceFileContext(){ String context=getServiceFileContext("test.txt"); System.out.println(context);
}
@Test
public void TestSftpRemove(){ if(remove("test.txt")){
System.out.println("删除文件成功");
} else{
System.out.println("删除文件失败"); }
}
}
配置文件 Sftp_UpDownload.properties ip=127.0.0.1 port=22
user=test psw=test
servicePath=testpath
下载的get方法详情 API /rangqiwei/article/details/9002046 上传的put方法详
情 API /longyg/archive/2012/06/25/2556576.html
方法一:
//上传文件代码
public class UploadFile
{
/// <summary>
/// 检查上传文件的大小
/// </summary>
/// <param name="fileUpload"></param>
/// <param name="maxSize"></param>
/// <returns></returns>
public static bool CheckSize(FileUpload fileUpload, int maxSize) {
return CheckSize(fileUpload.PostedFile, maxSize);
}
/// <summary>
/// 检查上传文件的大小
/// </summary>
/// <param name="file"></param>
/// <param name="maxSize"></param>
/// <returns></returns>
public static bool CheckSize(HttpPostedFile file, int maxSize) {
string filename = file.FileName;
int size = file.ContentLength;
if (size > 0 && size < maxSize)
{
return true;
}
return false;
}
/// <summary>
/// 检查上传文件的扩展名是否符合要求
/// </summary>
/// <param name="fileUpload"></param>
/// <param name="extNames">数组扩展名</param>
/// <returns></returns>
public static bool CheckType(FileUpload fileUpload, string[] extNames) {
foreach (string type in extNames)
{
string fileName = fileUpload.FileName;
string ext = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower(); if (ext.ToLower().Equals(ext))
return true;
return false;
}
return false;
}
private static bool CheckExtensionName(string fileName, string[] extNames) {
foreach (string ename in extNames)
{
string ext ="."+fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower(); if (ext.ToLower().Equals(extNames[0]) || ext.ToLower().Equals(extNames[1]) || ext.ToLower().Equals(extNames[2])
|| ext.ToLower().Equals(extNames[3]) || ext.ToLower().Equals(extNames[4]) || ext.ToLower().Equals(extNames[5]))
return false;
//return false;
}
return true;
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="fileUpload"></param>
/// <param name="webSavePath"></param>
/// <returns></returns>
public static bool Upload(FileUpload fileUpload, string webPath, bool isOLDName) {
if (fileUpload.HasFile)
{
string phyPath = HttpContext.Current.Server.MapPath(webPath);
string fileName = fileUpload.FileName;
string extName = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower(); string saveName = string.Empty;
if (isOLDName)
{
saveName = fileName.Substring(fileName.LastIndexOf("/") + 1);
}
else
{
string strDateTime = DateTime.Now.ToString("yyyyMMddHHmmss");
saveName = strDateTime + Guid.NewGuid().ToString().Substring(0, 8);
}
try
{
fileUpload.SaveAs(phyPath + saveName);
return true;
}
catch { }
}
return false;
}
/// <summary>
/// 转为jpg
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public System.Drawing.Image toJpg(Stream stream)
{
Bitmap bmp = new Bitmap(stream);
System.Drawing.Image image = bmp;//得到原图
//创建指定大小的图
System.Drawing.Image newImage = image.GetThumbnailImage(bmp.Width, bmp.Height, null, new IntPtr());
Graphics g = Graphics.FromImage(newImage);
g.DrawImage(newImage, 0, 0, newImage.Width, newImage.Height); //将原图画到指定图上
g.Dispose();
stream.Close();
return newImage;
}
/// <summary>
/// 上传文件,返回保存路径和文件名
/// </summary>
/// <param name="Request"></param>
/// <param name="webPath"></param>
public static IList<string> Save(HttpRequest Request, List<string> orgfileName, string webPath, string[] deniedFiles)
{
HttpFileCollection files = Request.Files;
List<string> url = new List<string>();
if (files.Count > 0)
{
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
if (file.ContentLength > 0)
{
string uploadFileName =
GenerateFileName(System.IO.Path.GetFileName(file.FileName));
string filePath = HttpContext.Current.Server.MapPath(webPath);
if (CheckExtensionName(file.FileName, deniedFiles))
{
if (!System.IO.Directory.Exists(filePath))
System.IO.Directory.CreateDirectory(filePath);
file.SaveAs(filePath + uploadFileName);
url.Add(filePath + uploadFileName);
orgfileName.Add(file.FileName.Substring(file.FileName.LastIndexOf("/") + 1)); }
}
}
}
return url;
}
/// <summary>
/// 计算文件长度
/// 徐丽
/// 20090910
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public static int SumContentLen(HttpRequest Request)
{
HttpFileCollection files = Request.Files;
int sum=0;
if (files.Count > 0)
{
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
sum += file.ContentLength;
}
}
return sum;
}
/// <summary>
/// 获取文件名
/// </summary>
/// <param name="orgFileName"></param>
/// <returns></returns>
private static string GenerateFileName(string orgFileName)
{
string saveName = string.Empty;
string strDateTime = DateTime.Now.ToString("yyyyMMddHHmmss"); saveName = strDateTime + Guid.NewGuid().ToString().Substring(0, 8); string extName = orgFileName.Split('.').Last();
return saveName +"."+extName;
}
}
//下载文件源码
public class DownloadFile : System.Web.UI.Page
{
/// <summary>
/// 文件下载
/// 徐丽
/// 2009-09-29
/// </summary>
/// <param name="fileUrl"></param>
/// <param name="fileName"></param>
/// <param name="Response"></param>
public void DownLoadFile(string fileUrl, string fileName, HttpResponse Response) {
string selectName = Server.MapPath("~/attachments/") + fileUrl;
string saveFileName = fileName;
//创建一个文件实体,方便对文件操作
FileInfo finfo = new FileInfo(selectName);
//清空输出流
Response.Clear();
Response.Charset = "utf-8";
Response.Buffer = true;
//关闭输出文件编码及类型和文件名
this.EnableViewState = false;
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + saveFileName);
//因为保存的文件类型不限,此处类型选择“unknown”
Response.ContentType = "application/unknown";
Response.WriteFile(selectName);
//清空并关闭输出流
Response.Flush();
Response.Close();
Response.End();
}
}
方法二:
**//// <summary>
/// WebClient上传文件至服务器
/// </summary>
/// <param name="fileNamePath">文件名,全路径格式</param>
/// <param name="uriString">服务器文件夹路径</param>
private void UpLoadFile(string fileNamePath,string uriString)
{
//string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);
NewFileName = DateTime.Now.ToString("yyMMddhhmmss") +
DateTime.Now.Millisecond.ToString() +
fileNamePath.Substring(fileNamePath.LastIndexOf("."));
string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1); if(uriString.EndsWith("/") == false) uriString = uriString + "/";
uriString = uriString + NewFileName;
/**//// 创建WebClient实例
WebClient myWebClient = new WebClient();
myWebClient.Credentials = CredentialCache.DefaultCredentials;
// 要上传的文件
FileStream fs = new FileStream(fileNamePath, FileMode.Open,
FileAccess.Read);
//FileStream fs = OpenFile();
BinaryReader r = new BinaryReader(fs);
try
{
//使用UploadFile方法可以用下面的格式
//myWebClient.UploadFile(uriString,"PUT",fileNamePath);
byte[] postArray = r.ReadBytes((int)fs.Length);
Stream postStream = myWebClient.OpenWrite(uriString,"PUT");
if(postStream.CanWrite)
{
postStream.Write(postArray,0,postArray.Length);
}
else
{
MessageBox.Show("文件目前不可写!");
}
postStream.Close();
}
catch
{
MessageBox.Show("文件上传失败,请稍候重试~");
}
}
/**//// <summary>
/// 下载服务器文件至客户端
/// </summary>
/// <param name="URL">被下载的文件地址,绝对路径</param>
/// <param name="Dir">另存放的目录</param>
public void Download(string URL,string Dir)
{
WebClient client = new WebClient();
string fileName = URL.Substring(URL.LastIndexOf("\\") + 1); //被下载的文件名
string Path = Dir+fileName; //另存为的绝对路径+文件名
try
{
WebRequest myre=WebRequest.Create(URL);
}
catch
{
//MessageBox.Show(exp.Message,"Error");
}
try
{
client.DownloadFile(URL,Path);
}
catch
{
//MessageBox.Show(exp.Message,"Error");
} }
20xx年检验科工作总结20xx年是我们医院和科室飞跃发展的一年。在搬进新院后,院容院貌焕然一新,各科业务量大幅增加,在这大好形势…
20xx年个人年度总结不知不觉间,来到XX单位已经有半年时间了,在项目开发的工作中,经历了很多酸甜苦辣,认识了很多良师益友,获得了…
坛子里有xx年考上海大学通信学院的帖子,这里我就对xx年考通信学院的经验补充一下,写得不好望学弟学妹们谅解。个人情况简单介绍一下,…
苏教版六年级数学下册知识点总结第一单元百分数的应用大分率-小分率=相差的分率实分率-计分率=实比计多的分率利息=本金X利率X时间实…
尊敬的各位领导、各位同事大家下午好:非常荣幸能够代表新员工站在这里发言,感谢各位领导和同事对我的信任,谢谢大家。十几年的学习生活匆…
一辩:FIRSTDEBATER二辩:SECONDDEBATER对方辩友,myfellowdebaters开始的陈词,Honorab…
车间盐酸罐泄漏事故演习总结20xx年xx月xx日下午,车间举行了一次盐酸罐泄漏事故演习。车间领导、技术管理人员及相关作业岗位人员共…
驻矿安监员安全工作总结进入七月份以来,我所驻煤矿认真贯彻落实上级部门文件、会议精神,全面认真落实“先抽后采、监测监控、以风定产”的…
我于XX年毕业于兰州医学院,响应党中央和政府的号召:到农村去,到基层去,到人民需要我们的地方去。于是我报考了我省的“三支一扶”计划…
狭义的汽车服务:新车进入流通领域,直至其使用后回收报废各个环节涉及的各类服务,以及整车出售及其后与汽车使用相关的服务。广义:自新车…