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

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-filesexamplePhoto.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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Combine that with 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);
        }
    }
}

Alternatively, use 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);
    }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x