0

I want to upload a file to a ftp server in my frontend.

I have tried

        IBrowserFile imgFile = e.File;
        var buffer = new byte[imgFile.Size];
        await imgFile.OpenReadStream().ReadAsync(buffer);
        
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://localhost:2121");
        request.Method = WebRequestMethods.Ftp.UploadFile;
        request.Credentials = new NetworkCredential("login", "password");
        using (FileStream fileStream = File.Open(imgFile.Name, FileMode.Open, FileAccess.Read))
        {
            using (Stream requestStream = request.GetRequestStream())
            {
                await requestStream.WriteAsync(buffer, 0, (int)imgFile.Size);
                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                {
                    Console.WriteLine($"Upload File Complete, status {response.StatusDescription}");
                }
            }
        }

However I am getting following error:

System.PlatformNotSupportedException: System.Net.Requests is not supported on this platform.

Looks like browser does not support this package.

Question: How to upload a file to a ftp server?

Elnur
  • 119
  • 1
  • 5
  • Does this answer your question? [Upload file to FTP using C#](https://stackoverflow.com/questions/15268760/upload-file-to-ftp-using-c-sharp) – Alejandro Aug 29 '22 at 16:26
  • @Alejandro System.Net.WebClient is not support in the browser. – Elnur Aug 29 '22 at 16:55

1 Answers1

0

According to this document, try this way:

await using FileStream fs = new(path, FileMode.Create);
await browserFile.OpenReadStream().CopyToAsync(fs);  

But I see it may be a picture, so try to use this method: BrowserFileExtensions.RequestImageFileAsync

Back to the error, I used to get this error, it's becasue the Asynchronous Programming Model (APM) (using IAsyncResult and BeginInvoke) is no longer the preferred method of making asynchronous calls. The Task-based Asynchronous Pattern (TAP) is the recommended async model as of .NET Framework 4.5. Because of this, and because the implementation of async delegates depends on remoting features not present in .NET Core, BeginInvoke and EndInvoke delegate calls are not supported in .NET Core. I'm not sure whether your problem is this or not. If you want more information about it, this blog may help.

Great day.

Xiaotian Yang
  • 499
  • 1
  • 2
  • 7
  • You miss understood the question. The problem is in opening FTP connection and uploading a file to a FTP server in Blazor. – Elnur Sep 11 '22 at 07:19
  • OK, ftp is not available if you are using blazor webassembly. It only can be done by using JS. If using blazor server, it's ok to use any FTP client library – Xiaotian Yang Sep 13 '22 at 09:17