我是Xamarin和C#世界的新手,我正尝试将图像上传到FTP服务器。我看到FtpWebRequest类可以做到这一点,但是我做的不对,我不知道如何注入平台特定的代码,我什至不知道它的真正含义,已经看过这个视频(https://www.youtube.com/watch?feature=player_embedded&v=yduxdUCKU1c),但是我看不到如何使用它来创建FtpWebRequest类并上传图像。
我看到此代码(在这里: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和File类型,我的FtpWebRequest类也没有“ KeepAlive”,“ UseBinary”和“ GetRequestStream”方法,并且我的Stream类没有“ Close”方法。
我的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类的完整示例?我只在上面找到像这样使用的类。
最佳答案
好的,我只是想出了方法,并且将向我展示如何做,我真的不知道这是否是更好和正确的方法,但是它确实有效。
首先,我必须在窗体项目上创建一个名为IFtpWebRequest的接口类,其中包含以下内容:
namespace Contato_Vistoria
{
public interface IFtpWebRequest
{
string upload(string FtpUrl, string fileName, string userName, string password, string UploadDirectory = "");
}
}
然后,在我的iOS / droid项目中,我必须创建一个实现IFtpWebRequest的类FTP,并在该类中编写上载函数(我现在正在使用另一个函数),这是ENTIRE 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项目中,它几乎是相同的,但是无论如何,我都会张贴它,以帮助像我这样的人,他们不了解太多,需要查看如何做的完整示例。这里是:
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上的一个按钮中的一个简单click事件中:
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(函数的参数)”,以更加具体。
这就是我的做法,希望我能帮助别人。