WebAPI method that takes a file upload and additional arguments WebAPI method that takes a file upload and additional arguments asp.net asp.net

WebAPI method that takes a file upload and additional arguments


You can create your own MultipartFileStreamProvider to access the additional arguments.

In ExecutePostProcessingAsync we loop through each file in multi-part form and load the custom data (if you only have one file you'll just have one object in the CustomData list).

class MyCustomData{    public int Foo { get; set; }    public string Bar { get; set; }}class CustomMultipartFileStreamProvider : MultipartMemoryStreamProvider{    public List<MyCustomData> CustomData { get; set; }    public CustomMultipartFileStreamProvider()    {        CustomData = new List<MyCustomData>();    }    public override Task ExecutePostProcessingAsync()    {        foreach (var file in Contents)        {            var parameters = file.Headers.ContentDisposition.Parameters;            var data = new MyCustomData            {                Foo = int.Parse(GetNameHeaderValue(parameters, "Foo")),                Bar = GetNameHeaderValue(parameters, "Bar"),            };            CustomData.Add(data);        }        return base.ExecutePostProcessingAsync();    }    private static string GetNameHeaderValue(ICollection<NameValueHeaderValue> headerValues, string name)    {        var nameValueHeader = headerValues.FirstOrDefault(            x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase));        return nameValueHeader != null ? nameValueHeader.Value : null;    }}

Then in your controller:

class UploadController : ApiController{    public async Task<HttpResponseMessage> Upload()    {        var streamProvider = new CustomMultipartFileStreamProvider();        await Request.Content.ReadAsMultipartAsync(streamProvider);        var fileStream = await streamProvider.Contents[0].ReadAsStreamAsync();        var customData = streamProvider.CustomData;        return Request.CreateResponse(HttpStatusCode.Created);    }}


I think the answers here are excellent. So others can see a somewhat simple example of how to pass data in addition to the file in summary form, included is a Javascript Function that makes the WebAPI call to the FileUpload Controller, and the snippet from the FileUpload Controller (in VB.net) that reads the additional data passed from Javascript.

Javascript:

            function uploadImage(files) {            var data = new FormData();            if (files.length > 0) {                data.append("UploadedImage", files[0]);                data.append("Source", "1")                var ajaxRequest = $.ajax({                    type: "POST",                    url: "/api/fileupload/uploadfile",                    contentType: false,                    processData: false,                    data: data                });

File Upload Controller:

        <HttpPost> _    Public Function UploadFile() As KeyValuePair(Of Boolean, String)        Try            If HttpContext.Current.Request.Files.AllKeys.Any() Then                Dim httpPostedFile = HttpContext.Current.Request.Files("UploadedImage")                Dim source = HttpContext.Current.Request.Form("Source").ToString()

So as you can see in the Javascript, the additional data passed is the "Source" key, and the value is "1". And as Chandrika has answered above, the Controller reads this passed data through "System.Web.HttpContext.Current.Request.Form("Source").ToString()".

Note that Form("Source") uses () (vs. []) as the controller code is in VB.net.

Hope this helps.


You can extract multiple files and multiple attributes in this way:

public async Task<HttpResponseMessage> Post(){    Dictionary<string,string> attributes = new Dictionary<string, string>();    Dictionary<string, byte[]> files = new Dictionary<string, byte[]>();    var provider = new MultipartMemoryStreamProvider();    await Request.Content.ReadAsMultipartAsync(provider);    foreach (var file in provider.Contents)    {        if (file.Headers.ContentDisposition.FileName != null)        {            var filename = file.Headers.ContentDisposition.FileName.Trim('\"');            var buffer = await file.ReadAsByteArrayAsync();            files.Add(filename, buffer);        } else        {            foreach(NameValueHeaderValue p in file.Headers.ContentDisposition.Parameters)            {                string name = p.Value;                if (name.StartsWith("\"") && name.EndsWith("\"")) name = name.Substring(1, name.Length - 2);                string value = await file.ReadAsStringAsync();                attributes.Add(name, value);            }        }    }    //Your code here      return new HttpResponseMessage(HttpStatusCode.OK);}