Search This Blog

Tuesday, May 12, 2015

Http Request To Upload File(s) To The Server In ASP.NET Web Api

Instructions: if you need to attach files to a http request to upload them to a server, here's basically what you need to do:

  1. In your api post method, you need to verify that the request contains files, via Request.Content.IsMimeMultipartContent
  2. Go through the files attached to the request, using HttpContext.Request.Files, casting them to HttpPostedFileBase.
  3. Now you do what you want with the files.
To test this using a http client like google's Advanced REST Client, simply mark the request as a post method, and you will be able to click a "Files" option, like the in the image below:


Usage:
            try
            {
                if (Request.Content.IsMimeMultipartContent())
                {
                    HttpFileCollectionBase files = this.UmbracoContext.HttpContext.Request.Files;
                    foreach (String uploadedFileName in files)
                    {
                        HttpPostedFileBase httpPostedFileBase = files[uploadedFileName] as HttpPostedFileBase;

                        /* do what you want with the file, here */
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

3 comments:

  1. Please post how to retrieve image by using web api from angularJS

    ReplyDelete
  2. Sorry, at this point I am not yet familiar with Angular, will not be able to help. I believe Stackoverflow will be of help.

    ReplyDelete