2

how the controller action of mvc4 should look like by posting file like this ?

Html

<form enctype="multipart/form-data">
  <input name="file" type="file" />
  <input type="button" value="Upload" />
</form>

Javascript

$(':button').click(function(){
    var formData = new FormData($('form')[0]);
    $.ajax({
        url: 'api/fileupload',  //server script to process data
        type: 'POST',
        xhr: function() {  // custom xhr
            var myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){ // check if upload property exists
                myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
            }
            return myXhr;
        },
        //Ajax events
        beforeSend: beforeSendHandler,
        success: completeHandler,
        error: errorHandler,
        // Form data
        data: formData,
        //Options to tell JQuery not to process data or worry about content-type
        cache: false,
        contentType: false,
        processData: false
    });
});
4
  • 1
    If you're posting to PHP, an ASP.NET MVC controller won't do you a lot of good :) Commented Jul 19, 2013 at 21:31
  • That will depend on what $.ajaxSettings.xhr() is and how it sends the file to server. You seem to be testing against some upload property on it. Looks like some custom built stuff. Just use FireBug to see what encoding is used and how the file is transmitted over the wire. If it uses multipart/form-data then its trivial to retrieve it. Commented Jul 19, 2013 at 21:35
  • Why its trivial. How should i know what microsoft except ? A trivial answer will be nice. It is encoded as multipart/form-data Commented Jul 19, 2013 at 21:41
  • 1
    It's trivial because if your client side code sends a multipart/form-data encoded content you could simply use an HttpPostedFileBase argument in your controller action which will contain the uploaded file. If your client code uses some other non-standard protocol for uploading the file to the server I am afraid that we cannot know how to answer your question without knowing how the file is transmitted. At the worst case if you are using some custom stuff you could access the raw InputStream of the request. Commented Jul 19, 2013 at 21:42

1 Answer 1

4

Looks like the normal MVC action for uploading a file will work:

[HttpPost]
public ActionResult fileupload(HttpPostedFileBase file)
{
    // do something with file.InputStream
}
Sign up to request clarification or add additional context in comments.

1 Comment

There is no mediatypeformatter for multipart/form-data. Can help: asp.net/web-api/overview/working-with-http/…

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.