Search code examples
c#.netrestfile-uploadwebapi

How to accept a file upload AND some data as a POST to a .NET REST API


I'm using the .NET WebAPI to self-host a REST API from my .NET application. I have configured a controller to accept your standard GETs and POSTs, but there is one case that I have yet to cover.

On the UI side, a user will fill out a form, including a path to a file to be uploaded, and this data + file should be posted to my server via its REST API when the user clicks submit. It's easy to design a POST method in my controller for just the data portion, but how do we also accept a file upload as part of that POST method?

An example of what my current method for receiving a post request without the file data is as follows:

        // public class EventsController : ApiController
        public HttpResponseMessage PostEvent(EventRow e)
        {
            // some database work here.
            if (e == null) { return BadRequest(e); }

            var validResponse = Request.CreateResponse<EventRow>(System.Net.HttpStatusCode.Created, e);
            string uri = Url.Link("API Default", new { id = e.Id });
            validResponse.Headers.Location = new Uri(uri);

            return validResponse;
        }

Solution

  • You can convert the file to a base64 encoded byte array and send that up as a property in the JSON object you're sending. No need for special headers, "application/json" and post will work just fine.

    Stack overflow question concerning using javascript to convert a file to a base64 encoded byte array.

    C# should just be File.WriteAllBytes(), or store the byte array in a database or other data store.