c# - 使用 PCL Xamarin Forms 将图像上传到 FTP 服务器

标签 c# ftp xamarin.forms image-uploading ftpwebrequest

我是 Xamarin 和 C# 世界的新手,我正在尝试将图像上传到 FTP 服务器。我看到 FtpWebRequest 类可以执行此操作,但我没有得到正确的结果,我不知道如何注入(inject)平台特定代码,我什至不知道它的真正含义,已经观看了此视频( 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 类:

公共(public)密封类 FtpWebRequest :WebRequest { 公共(public)覆盖字符串 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 的接口(interface)类,其中包含以下内容:

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

然后,在我的 iOS/droid 项目中,我必须创建一个名为 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 项目几乎相同,但无论如何我都会发布它,以帮助那些像我一样不太了解并且需要查看如何执行此操作的完整示例的人。这是:

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", "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcdbdddeced5d9d0fcd5dfd0d3c9d892dfd3d1" rel="noreferrer noopener nofollow">[email protected]</a>", "/pub/incoming"), "Ok");

        await Navigation.PopAsync();
    }

要调用该函数,您需要编写“DependencyService.Get().YourFunction(函数的参数)”,更具体地说。

我就是这样做的,希望可以帮助别人。

关于c# - 使用 PCL Xamarin Forms 将图像上传到 FTP 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42634536/

相关文章:

c# - 在 Xamarin Forms 中渲染 HTML 并从 HTML 链接打开嵌入的 PDF

c# - 如何更新 EF 中的相关实体(代码优先)

c# - 设置 Artist 字段时 Taglib 数组异常

java - 为什么 PathparentPath = Paths.get(strPath) 会改变分隔符?

java - org.apache.commons.net.ftp 的 FTPClient 类中的 EnterLocal...() 和 EnterRemote...() 方法之间的区别

.net - FTP使用.NET上传多个文件而无需断开连接

c# - 在 C# 中何时使用 'as' 以及何时使用 'is'

c# - 无法通过 websocket 将数据从服务器发送到客户端

c# - 使用 Xamarin Forms 播放视频

xamarin.forms - 将选择器选择的值绑定(bind)到属性 Xamarin.Forms