Thursday, 19 January 2017

Upload a image to Web Api method from the Windows forms client

In this post you are going to see how to call a web api method from windows forms client to upload image.



First we have to create a WebApi controller named BlogController with a method Post.

    public class CheckMimeMultiPart : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.Request.Content.IsMimeMultipartContent())
            {
                throw new               
                HttpResponseException(System.Net.HttpStatusCode.UnsupportedMediaType);
            }
        }
    }


    public class FilePostResult
    {
       
        public string FileName { set; get; }

        public string Url
        {
            set;get;
        }

        public long Size { set; get; }

    }


    public class BlogController : ApiController
    {
        public string Get()
        {
            return "testing";
        }


        [CheckMimeMultiPart]
        public async Task<FilePostResult> Post()
        {
            try
            {
                var path = HttpContext.Current.Server.MapPath("~/img");
                var streamprovider = new MultipartFormStreamProvider(path);
                await Request.Content.ReadAsMultipartAsync(streamprovider);


                var streamProvider = await Request.Content.ReadAsMultipartAsync(); // HERE
                foreach (var file in streamProvider.Contents)
                {
                    var imageFilename = file.Headers.ContentDisposition.FileName.Trim('\"');
                    var imageStream = await file.ReadAsStreamAsync();
                }

                var localfilename = streamprovider.FileData.Select(x => x.LocalFileName)
                                   .FirstOrDefault();

                var fileinfo = new FileInfo(localfilename);
                var response = new FilePostResult();

                response.FileName = fileinfo.Name;
                response.Size = fileinfo.Length;
                response.Url = Request.RequestUri.GetLeftPart(UriPartial.Authority) 
                                +"/img/" + response.FileName; ;

                return response;                               
                  
            }catch(Exception ex)
            {
                return new FilePostResult()
                {
                    FileName = "",
                    Size =0,
                    Url = Request.RequestUri.GetLeftPart(UriPartial.Authority)
                };
            }

        }
    }



web.config file changes for upload limit

<system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="30000000" />
      </requestFiltering>
    </security>
</system.webServer>


  <system.web>
    <httpRuntime targetFramework="4.6.1" maxRequestLength="30000000"  />  
  </system.web>



then create a windows forms, with one browse button and uplaod button with a link button to browse the uploaded image in the server. Image can be upload as multipart form data where image is send as stream content. we have to get the result using the ContinueWith options of Task factory class

This is the design of our windows forms.Create a delegate to update the control to avoid the cross thread exceptions.




    public partial class Form1 : Form
    {
        DialogResult result;

        public delegate void UpdateLink(string text);

        public void Update(string text)
        {
            linkLabel1.Links.Clear();
            linkLabel1.Text = text;
            linkLabel1.Links.Add(new LinkLabel.Link(0, text.Length, text));
          
        }

        private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start(e.Link.LinkData.ToString());
        }



        public Form1()
        {
            InitializeComponent();
           
      openFileDialog1.Filter = "Images (*.JPG;*.BMP;*.PNG;*.GIF)|*.JPG;*.BMP;*.PNG;*.GIF";
            openFileDialog1.Multiselect = true;
            openFileDialog1.Title = "Browse images";
            linkLabel1.LinkClicked += LinkLabel1_LinkClicked;
        }

        private void button1_Click(object sender, EventArgs e)
        {          
            result = openFileDialog1.ShowDialog();        
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string address = "http://localhost:57437/api/Blog";
            HttpClient client = new HttpClient();
            if (result == DialogResult.OK)
            {
             try
             {
               foreach (var item in openFileDialog1.FileNames)
               {
                 var stream = File.Open(item, FileMode.Open);

                 var multipartcontent = new MultipartFormDataContent();
                 
                 multipartcontent.Add(new StreamContent(stream), 
                                "\"postimage\""
                                string.Format("\"{0}\"", item));


    var resulttask = client.PostAsync(address, multipartcontent);

    resulttask.ContinueWith(x => {
        if (x.Status == TaskStatus.RanToCompletion)
           {
              
              var response = resulttask.Result;
              if (response.IsSuccessStatusCode)
               {
                     
                 var data = response.Content.ReadAsStringAsync().Result;
                 var postresult = JsonConvert.DeserializeObject<FilePostResult>(data);
                 linkLabel1.BeginInvoke(new UpdateLink(Update), postresult.Url);
  
                foreach (var header in response.Content.Headers)
                {
                   Debug.WriteLine("{0}: {1}", header.Key, string.Join(",", header.Value));
                }
                                
           }
        else
           {
             Debug.WriteLine("Response :" + response.Content.ReadAsStringAsync().Result);
           }
          }

         stream.Dispose();
                        
});
       }
     }
    catch (Exception ex)
    {

       
     }
   }
       
 }

    
}

When you click on the link button it will launch that url will launch in browser.












From this post you can learn how to upload a image from windows forms to Web api

1 comment:

  1. This is an amazing blog,it gives very helpful messages to us.Besides that Wisen has established as Best Dot Net Training in Chennai. or learn thru ASP.NET Online Training . Nowadays Dot Net has tons of job opportunities on various vertical industry.

    ReplyDelete