How to Upload Image to Server in C#

By FoxLearn 7/17/2024 4:22:06 AM   12.74K
To upload an image to a web server in a C# Windows Forms application, you can use the HttpClient class or RestSharp to send a POST request with the image data as a multipart form data.

How to Upload Image to Web Server in C#

Create a new Windows Forms Application project.

Drag and drop the PictureBox, Button, TextBox controls from the Visual Studio toolbox into your form designer, then design a simple UI allows you to display image to PictureBox, show image path to TextBox and upload image to server in c# as shown below.

c# winform upload image to server

How to call web api post method from windows application in c#

Right-clicking on your project, then select Manage Nuget Packages. Next, Search 'RestSharp', then download and install it.

c# restsharp

On the server side, you need a script to handle the uploaded image data and save it to the appropriate location on the server. If you don't know how to create a web api you can view this post How to Upload files in ASP.NET Core Web API using C#.

Adding a click event handler to the Upload button allows you to upload an image to server in c#.

private async void btnUpload_Click(object sender, EventArgs e)
{
    //c# open file dialog with image filters
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp; *.png)|*.jpg; *.jpeg; *.gif; *.bmp; *.png" })
    {
        // Get the file path from the use
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            //c# display image in picture box  
            pictureBox1.Image = new Bitmap(ofd.FileName);
            //c# show image file path  
            txtFileName.Text = ofd.FileName;
            //c# upload image to web server
            using (var fileStream = File.Open(ofd.FileName, FileMode.Open))
            {
                // Set the URL of the server script that handles the upload
                var client = new RestClient("http://localhost:11122/api/file/upload");
                var request = new RestRequest(Method.POST);
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    await fileStream.CopyToAsync(memoryStream);
                    request.AddFile("file", memoryStream.ToArray(), ofd.FileName);
                    request.AlwaysMultipartFormData = true;
                    var response = await client.ExecuteAsync(request);
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        dynamic json = JsonConvert.DeserializeObject(response.Content);
                        string fileName = json.fileName;
                        //Handling your code
                    }
                }
            }
        }
    }
}

Below is using HttpClient to upload files in c# windows forms

private async void btnUpload_Click(object sender, EventArgs e)
{
    //c# open file dialog with image filters
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp; *.png)|*.jpg; *.jpeg; *.gif; *.bmp; *.png" })
    {
        // Get the file path from the use
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            //c# display image in picture box  
            pictureBox1.Image = new Bitmap(ofd.FileName);
            //c# show image file path  
            txtFileName.Text = ofd.FileName;
            //c# upload image to web server
            using (var client = new HttpClient())
            {
                // Set the URL of the server script that handles the upload
                string url = "http://localhost:11122/api/file/upload";

                using (var content = new MultipartFormDataContent())
                {
                    // Add the image file to the content
                    string filePath = ofd.FileName;
                    byte[] fileBytes = File.ReadAllBytes(filePath);
                    content.Add(new ByteArrayContent(fileBytes), "file", Path.GetFileName(filePath));

                    // Send the POST request
                    HttpResponseMessage response = await client.PostAsync(url, content);

                    // Check the response status
                    if (response.IsSuccessStatusCode)
                    {
                        //Image uploaded successfully
                        dynamic json = JsonConvert.DeserializeObject(response.Content);
                        string fileName = json.fileName;
                        //Handling your code                    
                    }
                    else
                    {
                        //"Failed to upload image.
                    }
                }
            }
        }
    }
}

If you want to get the filename when the file is uploaded to the server. You need to install RestSharp.Newtonsoft.Json from Manage Nuget  Packages in your Visual Studio.

c# restsharp newtonsoft json

Through this post, i hope so you can understand how to upload image to server c# windows application via c# web api upload file with model asp.net core.