Javascript上传文件MVC4动作

时间:2013-07-19 21:29:46

标签: javascript asp.net-mvc asp.net-mvc-4

通过发布这样的文件,mvc4的控制器操作应该如何?

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

1 个答案:

答案 0 :(得分:4)

看起来上传文件的正常MVC操作会起作用:

[HttpPost]
public ActionResult fileupload(HttpPostedFileBase file)
{
    // do something with file.InputStream
}