zyllf2009 发表于 2015-11-6 10:56:10

asp.net 实现FTP上传

  我先说一下我的业务需求,我的项目部署在A服务器上,但是我的附件需要上传到B服务器上,所以我在B服务器上面部署了FTP,通过FTP实现附件的上传和下载。
  先说上传:
  首先,附件要先从客户端上传到本地服务器,即A服务器
  然后,再考虑从本地服务器A到异地服务器B,通过FTP,如下:

string url = url + "/" + dirName + "/sfax/" + fileName; //文件上传到ftp上的地址
int contentLen;
Stream strm = null;
FileStream fs = null;
FileInfo fileInf = new FileInfo(filePath);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));          // 根据uri创建FtpWebRequest对象
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);// ftp用户名和密码
reqFTP.KeepAlive = false;                                          // 默认为true,连接不会被关闭, 在一个命令之后被执行
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;                  // 指定执行什么命令
reqFTP.UseBinary = true;                                             // 指定数据传输类型
reqFTP.ContentLength = fileInf.Length;                               // 上传文件时通知服务器文件的大小
reqFTP.Timeout = 10 * 1000;
int buffLength = 2048;                                             // 缓冲大小设置为2kb
byte[] buff = new byte;
try
{
fs = fileInf.OpenRead();                     // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
strm = reqFTP.GetRequestStream();            // 把上传的文件写入流
contentLen = fs.Read(buff, 0, buffLength);   // 每次读文件流的2kb
while (contentLen != 0)                        // 流内容没有结束
{
strm.Write(buff, 0, contentLen);         // 把内容从file stream 写入 upload stream
contentLen = fs.Read(buff, 0, buffLength);
}
// 关闭两个流
strm.Close();
fs.Close();
}
catch
{
url = null;
}
finally
{
if (strm != null)
{
strm.Close();
}
if (fs != null)
{
fs.Close();
}
}
return url;
  需要说一下,FTP上传,最容易处错误的地方就是路径问题,
  在写这个程序的时候,
  strm = reqFTP.GetRequestStream(); // 把上传的文件写入流
  上面这行代码就总是抛异常,开始以为是权限问题,结果找来找去,发现时文件读取路径问题,所以大家在写程序的时候,也着重注意一下路径问题吧!
  下面说下载,异地服务器下载,也需要走两步,先从异地服务器下载到本地服务器,再从本地服务器下载到客户端,如下:
  我先说一下,我的代码,我在下载时,与当前页面的Jquery代码有冲突,所以下载提示框总是提示不出来,所以我在下载的时候,是弹出一张空白页面,然后在空白页面实现下载,就不用考虑Jquery的冲突问题了,如下:

function downFile1(id){
var str="../DownLoad.aspx?type=loadFaxFile&FID="+id+"&file=1";
window.open(str);
}
  

asp.net下载代码如下:

public void DownFileNow(string FID,string FileType)
    {
      FAX_FSENTBll bll = new FAX_FSENTBll();
      FAX_FSENTModel model = bll.GetModel(FID);
      string filePath = "";
      string LocalFilePath = Download(filePath);//下载附件到服务器本地
      //下载附件到客户端
      if (string.IsNullOrEmpty(LocalFilePath) == false)
      {
            if (File.Exists(LocalFilePath))
            {
                ByteFileDown(LocalFilePath, Path.GetFileName(LocalFilePath));
            }
      }
      else
      {
            MessageBox.Show(this, "没有找到要下载的文件!");
      }
    }/// <summary>
/// ftp服务器文件下载到本地服务器
/// </summary>
/// <param name=&quot;FtpPath&quot;>文件在ftp服务器路径</param>
/// <returns></returns>
private string Download(string FtpPath)
{
string EnteNum = userInfo.NumCode;
string EnteFileName = GetEnteFile(EnteNum);
string fileName = FtpPath.Substring(FtpPath.LastIndexOf(&quot;\\&quot;) + 1);
string url = &quot;ftp://&quot; + ftpServerIP + &quot;/faxdata/&quot; + EnteFileName + &quot;/sfax/&quot; + fileName;//异地服务器存放路径
string LoaclFilePath = getWebPath(EnteFileName) + &quot;\\&quot; + fileName;//文件本地服务器存放路径
if (File.Exists(LoaclFilePath)) //如果文件存在本地服务器,就不需要从ftp上再次下载了
return LoaclFilePath;
FileStream fs = null;
Stream responseStream = null;
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(url));
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();//获取一个请求响应对象
responseStream = response.GetResponseStream();//获取请求的响应流
if (File.Exists(LoaclFilePath))//判断本地文件是否存在,如果存在,则打开和重写本地文件
fs = File.Open(LoaclFilePath, FileMode.Open, FileAccess.ReadWrite);
else                  //判断本地文件是否存在,如果不存在,则创建本地文件
fs = File.Create(LoaclFilePath);
if (fs != null)
{
int buffer_count = 65536;
byte[] buffer = new byte;
int size = 0;
while ((size = responseStream.Read(buffer, 0, buffer_count)) > 0)
{
fs.Write(buffer, 0, size);
}
fs.Flush();
fs.Close();
responseStream.Close();
}
return LoaclFilePath;
}
catch
{
return null;
}
finally
{
if (fs != null)
fs.Close();
if (responseStream != null)
responseStream.Close();
}

}/// <summary>
    /// 流的方式下载文件
    /// </summary>
    /// <param name=&quot;path&quot;>文件路径</param>
    /// <param name=&quot;filename&quot;>显示文件名</param>
    public static void ByteFileDown(string path, string filename)   //此方法可实现从本地服务器下载到客户端
    {
      try
      {
            FileStream fs = File.OpenRead(path);
            byte[] array = new byte;
            fs.Read(array, 0, (int)fs.Length);
            fs.Close();
            HttpContext.Current.Response.ContentType = &quot;application/octet-stream&quot;;
            HttpContext.Current.Response.AddHeader(&quot;Content-Disposition&quot;, &quot;attachment;FileName=&quot; + filename);
            HttpContext.Current.Response.BinaryWrite((byte[])array);
            HttpContext.Current.ApplicationInstance.CompleteRequest();
      }
      catch (Exception ex)
      {
            throw ex;
      }
      finally { }
    }
  

就是这样,其实在做FTP相关上传下载时,技术上就在搭建FTP服务器和代码上,当然,这对会的人不是难度,只对我这种什么都需要研究的人才有难度,在编写上传下载时,慎重考虑的就是保证路径的正确。
  写的不好,希望能帮助到需要的人!
  

版权声明:本文为博主原创文章,未经博主允许不得转载。
页: [1]
查看完整版本: asp.net 实现FTP上传