2014-02-26 178 views
1

我想知道这段代码有什么问题?林主办000webhost的一个ftp,我想使用的OpenFileDialog功能FTP上传图片

按钮打开图像,关于我的程序的用户从那里的电脑打开上传图片:

 OpenFileDialog open = new OpenFileDialog(); 
     if (open.ShowDialog() == DialogResult.OK) 
     { 
      Bitmap bit = new Bitmap(open.FileName); 
      pictureBox1.Image = bit; 
      pictureBox2.Image = bit; 
      bit.Dispose(); 
      string fullPath = open.FileName; 
      string fileName = open.SafeFileName; 
      string path = fullPath.Replace(fileName, ""); 
      User.Details.UpLoadImage(fullPath); 
     } 

上传它的代码:

try 
     { 
      String sourcefilepath = source; // e.g. “d:/test.docx” 
      String ftpurl = "ftp://www.locu.site90.com/public_html/"; // e.g. ftp://serverip/foldername/foldername 
      String ftpusername = "********"; // e.g. username 
      String ftppassword = "********"; // e.g. password 
      string filename = Path.GetFileName(source); 
      string ftpfullpath = ftpurl; 
      FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath); 
      ftp.Credentials = new NetworkCredential(ftpusername, ftppassword); 

      ftp.KeepAlive = true; 
      ftp.UseBinary = true; 
      ftp.Method = WebRequestMethods.Ftp.UploadFile; 

      FileStream fs = File.OpenRead(source); 
      byte[] buffer = new byte[fs.Length]; 
      fs.Read(buffer, 0, buffer.Length); 
      fs.Close(); 

      Stream ftpstream = ftp.GetRequestStream(); 
      ftpstream.Write(buffer, 0, buffer.Length); 
      ftpstream.Close(); 
     } 
     catch (Exception ex) 
     { 
      throw ex; 
     } 
    } 

我不断收到一些errrors “请求的URI是这个FTP命令无效” 和第二个错误是 “远程服务器返回错误:(530)尚未登录。“

+0

也许服务器要求安全连接(SSL),ftp.EnableSSL =真。 – user2453734

+0

如何解决? – user3354197

+0

不正确的URL可以通过更改url来包含文件名在末尾来解决:String ftpurl =“ftp://www.locu.site90.com/public_html/test.txt”;你可能打算做字符串ftpfullpath = ftpurl + filename;? – user2453734

回答

1

由于您正在进行上传。目标文件名称在FTP URL中是必需的。看起来这是你可能的预期与以下行做:

string ftpfullpath = ftpurl; 

尝试将其更改为:

string ftpfullpath = ftpurl + filename; 

对于错误没有登录,有的托管公司只允许安全连接。你可以尝试添加以下行代码:

ftp.EnableSsl = true; 
+0

嗨。我做了你的代码,修复了我的第一个错误。我正在接收第二个错误 - 在App.exe中发生未处理的异常类型'System.Net.WebException' 附加信息:远程服务器返回错误:(530)未登录。 – user3354197

+0

您确定凭据是正确的?我会使用类似filezilla的东西,并确保你可以先通过工具连接。然后一旦有效。然后尝试编码它。 – user2453734

+0

我做了您的enableSsl修复并修复了它。你有什么想法,为什么现在把这个错误扔给我? - App.exe中发生未处理的异常类型'System.Net.WebException' 附加信息:远程服务器返回错误:(500)语法错误,命令无法识别。 – user3354197

0

我使用这个方法,而且运作良好:

public static void UpLoadImage(string image, string targeturl) 
     { 
      FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://www.website.com/images/" + targeturl); 
      req.UseBinary = true; 
      req.Method = WebRequestMethods.Ftp.UploadFile; 
      req.Credentials = new NetworkCredential("user", "pass"); 
      byte[] fileData = File.ReadAllBytes(image); 
      req.ContentLength = fileData.Length; 
      Stream reqStream = req.GetRequestStream(); 
      reqStream.Write(fileData, 0, fileData.Length); 
      reqStream.Close(); 
     }