sftp文件上传和下载

sftp文件上传和下载

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

 

第二篇:C#文件上传与下载

方法一:

//上传文件代码

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");

} }

相关推荐