上传表格:

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




控制器/文件上传:

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);
    }
}


问题:

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

最佳答案

使用IFormFile.CopyToIFormFile.OpenReadStream访问上载文件的内容。

尽管WebClient无法与Stream interface一起使用。因此,您最好使用FtpWebRequest

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

    using (Stream ftpStream = request.GetRequestStream())
    {
        file.CopyTo(ftpStream);
    }
}

关于c# - 通过HTTP将文件上传到ASP.NET,再上传到C#中的FTP服务器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55499008/

10-11 22:51
查看更多