老外那弄来的一段FTP上传的代码

本文介绍了一种基于.NET的FTP图片上传控件实现方法,包括设置FTP请求参数、读取文件并上传到指定服务器的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 最近做了个仿网易的图片上传控件,为ftp上传伤了不少脑筋。在网上找了很多这方面的资料,但都不是很理想。后来在codeproject上找到了个老外写的图片上传控件,在上面剽窃了段代码过来用,没有国内网友发的那么多累赘代码,效果也很好!

  1. private void Upload(string filename)
  2.         {
  3.             FileInfo fileInf = new FileInfo(filename);
  4.             string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
  5.             FtpWebRequest reqFTP;
  6.             // Create FtpWebRequest object from the Uri provided
  7.             reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/wwwroot/upload/test/" + fileInf.Name));
  8.             // Provide the WebPermission Credintials
  9.             reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  10.             // By default KeepAlive is true, where the control connection is not closed
  11.             // after a command is executed.
  12.             reqFTP.KeepAlive = false;
  13.             // Specify the command to be executed.
  14.             reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
  15.             // Specify the data transfer type.
  16.             reqFTP.UseBinary = true;
  17.             // Notify the server about the size of the uploaded file
  18.             reqFTP.ContentLength = fileInf.Length;
  19.             // The buffer size is set to 2kb
  20.             int buffLength = 2048;
  21.             byte[] buff = new byte[buffLength];
  22.             int contentLen;
  23.             // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
  24.             FileStream fs = fileInf.OpenRead();
  25.             try
  26.             {
  27.                 // Stream to which the file to be upload is written
  28.                 Stream strm = reqFTP.GetRequestStream();
  29.                 // Read from the file stream 2kb at a time
  30.                 contentLen = fs.Read(buff, 0, buffLength);
  31.                 // Till Stream content ends
  32.                 while (contentLen != 0)
  33.                 {
  34.                     // Write Content from the file stream to the FTP Upload Stream
  35.                     strm.Write(buff, 0, contentLen);
  36.                     contentLen = fs.Read(buff, 0, buffLength);
  37.                 }
  38.                 // Close the file stream and the Request Stream
  39.                 strm.Close();
  40.                 fs.Close();
  41.             }
  42.             catch (Exception ex)
  43.             {
  44.                 MessageBox.Show(ex.Message, "Upload Error");
  45.             }
  46.         }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值