0

I have been reading around building an action method in my Web Api to allow the posting of images, which would be saved on the server and related to a Contact object via a field imageURL.

I have found a few examples online of how to set this up, and am wanting to test them. I currently have:

public Task<HttpResponseMessage> PostFile() 
{ 
    HttpRequestMessage request = this.Request; 
    if (!request.Content.IsMimeMultipartContent()) 
    { 
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 
    } 

    string root = System.Web.HttpContext.Current.Server.MapPath("~/Content/images"); 
    var provider = new MultipartFormDataStreamProvider(root); 

    var task = request.Content.ReadAsMultipartAsync(provider). 
        ContinueWith<HttpResponseMessage>(o => 
    { 

        string file1 = provider.BodyPartFileNames.First().Value;
        //Use file name to update ImageURL of contact

        return new HttpResponseMessage() 
        { 
            Content = new StringContent("File uploaded.") 
        }; 
    } 
    ); 
    return task; 
}

from How To Accept a File POST, and whilst I understand the flow I want to test it properly.

What would an example of a client call be to this API method, where I can include the contactid as a header?

I need to understand this properly to test this code sample so I can start understanding this more, but I'm really new to this area. I have kind of a chicken and egg scenario where I understand little about posting and receiving images and need a start point.

Thanks.

Community
  • 1
  • 1
JonnyKnottsvill
  • 1,123
  • 2
  • 16
  • 39

1 Answers1

0

You can use a small MVC or ASP application (you only need one page) where you can use some JS plugins to post files to your controller. Plugins: jQueryFileUpload or DropzoneJS. The last one is more easy to integrate. Both plugins has support for sending additional data.

Trasnea Daniel
  • 307
  • 2
  • 12
  • Thanks, I'll take a look! If they are drag 'n' drop, how would an API POST call to this page look? – JonnyKnottsvill Oct 23 '15 at 09:55
  • See above. I didn't tag the comment – JonnyKnottsvill Oct 23 '15 at 11:58
  • You can check the request payload using for DevTools (press F12) on Chrome an then Network tab. After that you press on the the request and You will see something similar with this [post](http://chxo.com/be2/20050724_93bf.html). – Trasnea Daniel Oct 27 '15 at 16:46
  • The `MultipartFormDataStreamProvider` class will handle the file and will parse the additional form data fields. After upload complete you can access `provider.FormData` and `provider.FileData` to get the serialized fields and access the file. – Trasnea Daniel Oct 27 '15 at 16:55