我的视图中有一个文件

<form id="upload" enctype="multipart/form-data">
   <input type="file" name="fileUpload" id="fileUpload" size="23" />
</form>

还有一个ajax请求

$.ajax({
    url: '<%=Url.Action("JsonSave","Survey")  %>',
    dataType: 'json',
    processData: false,
    contentType: "multipart/mixed",
    data: {
        Id: selectedRow.Id,
        Value: 'some date was added by the user here :))'
    },
    cache: false,
    success: function (data) {}
});

but there is no file in the Request.Files. Whats wrong with the ajax request?

推荐答案

Upload files using AJAX in ASP.Net MVC

Things have changed since HTML5

JavaScript

document.getElementById('uploader').onsubmit = function () {
    var formdata = new FormData(); //FormData object
    var fileInput = document.getElementById('fileInput');
    //Iterating through each files selected in fileInput
    for (i = 0; i < fileInput.files.length; i++) {
        //Appending each file to FormData object
        formdata.append(fileInput.files[i].name, fileInput.files[i]);
    }
    //Creating an XMLHttpRequest and sending
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/Home/Upload');
    xhr.send(formdata);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText);
        }
    }
    return false;
}   

Controller

public JsonResult Upload()
{
    for (int i = 0; i < Request.Files.Count; i++)
    {
        HttpPostedFileBase file = Request.Files[i]; //Uploaded file
        //Use the following properties to get file's name, size and MIMEType
        int fileSize = file.ContentLength;
        string fileName = file.FileName;
        string mimeType = file.ContentType;
        System.IO.Stream fileContent = file.InputStream;
        //To save file, use SaveAs method
        file.SaveAs(Server.MapPath("~/")+ fileName ); //File will be saved in application root
    }
    return Json("Uploaded " + Request.Files.Count + " files");
}

EDIT : The HTML

<form id="uploader">
    <input id="fileInput" type="file" multiple>
    <input type="submit" value="Upload file" />
</form>

Jquery相关问答推荐

当我使用 OwlCarousel 时,没有任何显示

如何定位 prism.js 脚本中包含的代码?

动态加载 css 样式表在 IE 上不起作用

元素上的 jQuery Change 事件 - 有什么方法可以保留以前的值?

在 Javascript 中启用和禁用 Div 及其元素

如何判断输入日期是否等于今天的日期?

无法在被动事件侦听器中阻止默认值

JavaScript 吸管(告诉鼠标光标下像素的 colored颜色 )

如何在不导致页面滚动的情况下删除位置哈希?

为特定请求禁用 ajaxStart() 和 ajaxStop()

从 iframe 访问父窗口的元素

聚焦 时防止 iphone 默认键盘

jquery 从特定表单获取所有输入

验证外部脚本是否已加载

在完成前一个请求之前中止新的 AJAX 请求

jQuery、复选框和 .is(":checked")

如何使用 JQuery 获取 GET 和 POST 变量?

如何在调用 Ajax 等异步调用时让代码等待

将数据发布到 JsonP

bootstrap 日期和时间 Select 器