2017-03-06 32 views
2

私はXamarinとC#worldで新しく、FTPサーバーに画像をアップロードしようとしています。私はFtpWebRequestクラスを見ましたが、私は正しいことを得ていません、プラタフォーム固有のコードを挿入する方法はわかりませんし、実際には何を意味するのか分からず、既にこのビデオを見ていましたが(https://www.youtube.com/watch?feature=player_embedded&v=yduxdUCKU1c)これを使ってFtpWebRequestクラスを作成し、画像をアップロードする方法を見てください。PCL Xamarinフォームを使用してFTPサーバーに画像をアップロード

私はこのコード(ここでは: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」方法を、持っているdoens'tと私の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を実装するクラスcaled FTPを作成する必要がありました/ドロイドプロジェクト私のiOSの内部で、

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

その後:

まず私は、まさにこの含まれている私のフォームプロジェクトにIFtpWebRequestと呼ばれるインタフェースクラスを作成する必要がありました

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プロジェクトで同じだが、私はとにかくそれを投稿します:そのクラス内で私がアップロード機能を(私は今、別のものを使用しています)、ここでは全体のFTPクラスの書きました私に似ていて、あまり分かっていなくて、必要がある人を助けてそれを行う方法の完全な例。ここでは、次のとおりです。

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フォームプロジェクトで、これは私が関数を呼び出した方法です。

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(関数のパラメータ)」を書くために必要な機能を呼び出すために:私のGUIのボタンから簡単なクリックイベントの内部。

それは私がそれをした方法です、私が誰かを助けることができることを願っています。

関連する問題