2017-03-06 87 views
2

我是Xamarin和C#世界的新手,我试图将图像上传到FTP服务器。我看到了FtpWebRequest类来做到这一点,但我没有得到它的权利,我不知道如何注入plataform特定的代码,我甚至不知道它的真正含义,已经看过这个视频(https://www.youtube.com/watch?feature=player_embedded&v=yduxdUCKU1c),但我不知道看不到如何使用它来创建FtpWebRequest类并上传图像。使用PCL将图像上传到FTP服务器Xamarin Forms

我看到了这段代码(这里是:https://forums.xamarin.com/discussion/9052/strange-behaviour-with-ftp-upload)发送一个图片,我无法使用它。

public void sendAPicture(string picture) 
{ 

    string ftpHost = "xxxx"; 

    string ftpUser = "yyyy"; 

    string ftpPassword = "zzzzz"; 

    string ftpfullpath = "ftp://myserver.com/testme123.jpg"; 

    FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath); 

    //userid and password for the ftp server 

    ftp.Credentials = new NetworkCredential(ftpUser, ftpPassword); 

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

    FileStream fs = File.OpenRead(picture); 

    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(); 
    ftpstream.Flush(); 

    // fs.Flush(); 

} 

我没有一个类型的FileStream,WebRequestMethods和文件,也是我的FtpWebRequest类好好尝试一下具有“保持活动”,“UseBinary”和“GetRequestStream”的方法,我的Stream类不具有“关闭“方法。

我的FtpWebRequest类:

公共密封类的FtpWebRequest:WebRequest的 { 公共重写字符串的ContentType { 得到 { 抛出新NotImplementedException(); }

set 
    { 
     throw new NotImplementedException(); 
    } 
} 

public override WebHeaderCollection Headers 
{ 
    get 
    { 
     throw new NotImplementedException(); 
    } 

    set 
    { 
     throw new NotImplementedException(); 
    } 
} 

public override string Method 
{ 
    get 
    { 
     throw new NotImplementedException(); 
    } 

    set 
    { 
     throw new NotImplementedException(); 
    } 
} 

public override Uri RequestUri 
{ 
    get 
    { 
     throw new NotImplementedException(); 
    } 
} 

public override void Abort() 
{ 
    throw new NotImplementedException(); 
} 

public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) 
{ 
    throw new NotImplementedException(); 
} 

public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) 
{ 
    throw new NotImplementedException(); 
} 

public override Stream EndGetRequestStream(IAsyncResult asyncResult) 
{ 
    throw new NotImplementedException(); 
} 

public override WebResponse EndGetResponse(IAsyncResult asyncResult) 
{ 
    throw new NotImplementedException(); 
} 

}

(我知道,我没写任何东西在那里,只是按了CTRL +。因为我不知道该怎么写有)

有谁可以提供我是一个FtpWebRequest类的完整样本?我只在上面找到这个类。

回答

2

好吧,我只是想出了如何做到这一点,我会告诉我是怎么做的,我真的不知道是否是更好,更正确的方法,但它的工作原理。

首先我要创建我的形式的项目称为IFtpWebRequest一个接口类,其中包含正是这一点:

namespace Contato_Vistoria 
{ 
     public interface IFtpWebRequest 
     { 
      string upload(string FtpUrl, string fileName, string userName, string password, string UploadDirectory = ""); 
     } 
} 

然后,我的iOS /机器人项目中,我不得不创建一个类caled FTP实现IFtpWebRequest而这个类里面我写的上传功能(我现在使用另一个),这里就是整个FTP类:

using System; 
using System.IO; 
using System.Net; 
using Contato_Vistoria.Droid; //My droid project 

[assembly: Xamarin.Forms.Dependency(typeof(FTP))] //You need to put this on iOS/droid class or uwp/etc if you wrote 
namespace Contato_Vistoria.Droid 
{ 
    class FTP : IFtpWebRequest 
    { 
     public FTP() //I saw on Xamarin documentation that it's important to NOT pass any parameter on that constructor 
     { 
     } 

     /// Upload File to Specified FTP Url with username and password and Upload Directory if need to upload in sub folders 
     ///Base FtpUrl of FTP Server 
     ///Local Filename to Upload 
     ///Username of FTP Server 
     ///Password of FTP Server 
     ///[Optional]Specify sub Folder if any 
     /// Status String from Server 
     public string upload(string FtpUrl, string fileName, string userName, string password, string UploadDirectory = "") 
     { 
      try 
      { 

       string PureFileName = new FileInfo(fileName).Name; 
       String uploadUrl = String.Format("{0}{1}/{2}", FtpUrl, UploadDirectory, PureFileName); 
       FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(uploadUrl); 
       req.Proxy = null; 
       req.Method = WebRequestMethods.Ftp.UploadFile; 
       req.Credentials = new NetworkCredential(userName, password); 
       req.UseBinary = true; 
       req.UsePassive = true; 
       byte[] data = File.ReadAllBytes(fileName); 
       req.ContentLength = data.Length; 
       Stream stream = req.GetRequestStream(); 
       stream.Write(data, 0, data.Length); 
       stream.Close(); 
       FtpWebResponse res = (FtpWebResponse)req.GetResponse(); 
       return res.StatusDescription; 

      } 
      catch(Exception err) 
      { 
       return err.ToString(); 
      } 
     } 
    } 
} 

这几乎是我的iOS项目相同,但无论如何,我会张贴于帮助像我这样不太了解和需要的人ee完整的例子如何做到这一点。这里是:

using System; 
using System.Net; 
using System.IO; 
//Only thing that changes to droid class is that \/ 
using Foundation; 
using UIKit; 
using Contato_Vistoria.iOS; 


[assembly: Xamarin.Forms.Dependency(typeof(FTP))] 
namespace Contato_Vistoria.iOS // /\ 
{ 
    class FTP : IFtpWebRequest 
    { 
     public FTP() 
     { 

     } 

     /// Upload File to Specified FTP Url with username and password and Upload Directory if need to upload in sub folders 
     ///Base FtpUrl of FTP Server 
     ///Local Filename to Upload 
     ///Username of FTP Server 
     ///Password of FTP Server 
     ///[Optional]Specify sub Folder if any 
     /// Status String from Server 
     public string upload(string FtpUrl, string fileName, string userName, string password, string UploadDirectory = "") 
     { 
      try 
      { 
       string PureFileName = new FileInfo(fileName).Name; 
       String uploadUrl = String.Format("{0}{1}/{2}", FtpUrl, UploadDirectory, PureFileName); 
       FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(uploadUrl); 
       req.Proxy = null; 
       req.Method = WebRequestMethods.Ftp.UploadFile; 
       req.Credentials = new NetworkCredential(userName, password); 
       req.UseBinary = true; 
       req.UsePassive = true; 
       byte[] data = File.ReadAllBytes(fileName); 
       req.ContentLength = data.Length; 
       Stream stream = req.GetRequestStream(); 
       stream.Write(data, 0, data.Length); 
       stream.Close(); 
       FtpWebResponse res = (FtpWebResponse)req.GetResponse(); 
       return res.StatusDescription; 

      } 
      catch (Exception err) 
      { 
       return err.ToString(); 
      } 
     } 
    } 
} 

最后,回到我的Xamarin Forms项目,这是我如何调用函数。从里面一个按钮在我的GUI简单的单击事件:

protected async void btConcluidoClicked(object sender, EventArgs e) 
    { 
     if (Device.OS == TargetPlatform.Android || Device.OS == TargetPlatform.iOS) 
      await DisplayAlert("Upload", DependencyService.Get<IFtpWebRequest>().upload("ftp://ftp.swfwmd.state.fl.us", ((ListCarImagesViewModel)BindingContext).Items[0].Image, "Anonymous", "[email protected]", "/pub/incoming"), "Ok"); 

     await Navigation.PopAsync(); 
    } 

要叫你需要写“DependencyService.Get()yourFunction中(函数的参数)。”,更具体的功能。

而这就是我做到这一点,希望我能帮助别人。

相关问题