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

Cor*_*rnJ 2 .net c# asp.net ftp webrequest

上传表格:

<form asp-action="Upload" asp-controller="Uploads" enctype="multipart/form-data">
<input type="file" name="file" maxlength="64" />
<button type="submit">Upload</button>
Run Code Online (Sandbox Code Playgroud)

控制器/文件上传:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

问题:

出现错误“找不到文件 xxxx”。我知道问题在于它试图在"C:\path-to-vs-files\examplePhoto.jpg"FTP 服务器上查找该文件,但该文件显然不存在。我一直在这里查看许多问题/答案,我认为我需要某种FileStream读/写代码。但我目前还没有完全理解这个过程。

Mar*_*ryl 8

使用IFormFile.CopyToIFormFile.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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)