将通过 HTTP 上传到 ASP.NET 的文件进一步上传到 C# 中的 FTP 服务器

Upload file uploaded via HTTP to ASP.NET further to FTP server in C#

上传表格:

<form asp-action="Upload" asp-controller="Uploads" enctype="multipart/form-data">
<input type="file" name="file" maxlength="64" />
<button type="submit">Upload</button>

Controller/File上传:

public void Upload(IFormFile file){
    using (WebClient client = new WebClient())
    {
        client.Credentials = new NetworkCredential("xxxx", "xxxx");
        client.UploadFile("ftp://xxxx.xxxx.net.uk/web/wwwroot/images/", "STOR", file.FileName);
    }
}

问题:

获取错误 "Could not find file xxxx"。我知道问题是它试图在 FTP 服务器上找到 "C:\path-to-vs-files\examplePhoto.jpg" 的文件,这显然不存在。我在这里看了很多 questions/answers,我想我需要某种 FileStream read/write 鳕鱼。但是我目前还没有完全理解这个过程。

使用IFormFile.CopyTo or IFormFile.OpenReadStream访问上传文件的内容。

将其与 WebClient.OpenWrite 合并:

public void Upload(IFormFile file)
{
    string url = "ftp://ftp.example.com/remote/path/file.zip";
    using (WebClient client = new WebClient())
    {
        client.Credentials = new NetworkCredential("xxxx", "xxxx");
        using (var ftpStream = client.OpenWrite(url))
        {
            file.CopyTo(ftpStream);
        }
    }
}

或者,使用 FtpWebRequest:

public void Upload(IFormFile file)
{
    string url = "ftp://ftp.example.com/remote/path/file.zip";
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
    request.Credentials = new NetworkCredential("username", "password");
    request.Method = WebRequestMethods.Ftp.UploadFile;  
    
    using (Stream ftpStream = request.GetRequestStream())
    {
        file.CopyTo(ftpStream);
    }
}