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

问题描述:

上传表格:

<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读/写鳕鱼.但是我目前还不完全了解这个过程.

Getting error "Could not find file xxxx". I understand the issue is that it's trying to find the file as it is "C:\path-to-vs-files\examplePhoto.jpg" on the FTP server, which obviously doesn't exist. I've been looking at many questions/answers on here and I think I need some kind of FileStream read/write cod. But I'm not fully understanding the process at the moment.

使用 IFormFile.CopyTo IFormFile.OpenReadStream 以访问上载文件的内容.

Use IFormFile.CopyTo or IFormFile.OpenReadStream to access the contents of the uploaded file.

尽管 WebClient 无法使用 Stream界面.因此,最好使用 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);
    }
}