6

I'm using jQuery ajax to upload file but want to add some parameters on webapi method, here is:

var data = new FormData();
data.append("file", $("#file")[0].files[0]);
data.append("myParameter", "test"); // with this param i get 404

$.ajax({
    url: '/api/my/upload/',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function (data) {
        console.log(data);
    }
});

The Webapi controller:

public class MyController : ApiController
{
    public string Upload(string myParameter)
    {
        return System.Web.HttpContext.Current.Request.Files.Count.ToString() + " / " + myParameter;
    }
}

Without myParameter everything work but when I include myParameter on formdata and api method I get 404, any chance to make it work?

1
  • mate can you post the complete code which is working for you . i seems to find it hard to get one better solution . cheers Commented Jul 21, 2014 at 17:04

1 Answer 1

13

Posting the FormData object results in a request with content type multipart/form-data. You have to read the request content like so:

[HttpPost]
public async Task<string> Upload()
{
    var provider = new MultipartFormDataStreamProvider("C:\\Somefolder");
    await Request.Content.ReadAsMultipartAsync(provider);

    var myParameter = provider.FormData.GetValues("myParameter").FirstOrDefault();
    var count = provider.FileData.Count;

    return count + " / " + myParameter;
}

BTW, this will save the file in the path specified, which is C:\\SomeFolder and you can get the local file name using provider.FileData[0].LocalFileName;

Please take a look at MSDN code sample and Henrik's blog entry.

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

2 Comments

This looks promising for my scenario; but how does a C# (not jQuery) client call this method? I need to pass two string args AND an XML file.
Task<string> getting error at this point . any ideas how to pass observable array and file to controller . cheers

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.