0

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;
        }
Jim
  • 4,509
  • 16
  • 50
  • 80

2 Answers2

3

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.

Community
  • 1
  • 1
JPK
  • 683
  • 6
  • 7
1

HttpRequest.Files should contain the uploaded binary to be used how you please. You will likely need to access this manually within the Action Method of the Controller.

Note that the file collection is populated only when the HTTP request content-type value is "multipart/form-data".

Haney
  • 32,775
  • 8
  • 59
  • 68
  • 1
    Interesting... I have a .NET client I'm using to test the API which is using HttpClient.PostAsync to satisfy my post requests. From HttpClient, I see that we can set the default request headers. What I'm using is: ``client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));``. In this case, I should use multipart/form-data instead of application/json, but how is that possibly enforced on the server side? – Jim May 06 '14 at 16:49
  • Tricky point. Maybe do the operations separately? AJAX requests for upload and data post? – Haney May 06 '14 at 17:28