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;
        }

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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".

2 Comments

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?
Tricky point. Maybe do the operations separately? AJAX requests for upload and data post?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.