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

▼魔方 西西 提交于 2019-12-01 10:58:30

问题


Upload form:

<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 upload:

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

Problem:

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.


回答1:


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

Though WebClient cannot work with Stream interface. So you better use 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);
    }
}


来源:https://stackoverflow.com/questions/55499008/upload-file-uploaded-via-http-to-asp-net-further-to-ftp-server-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!