jQuery的ajax上传文件在asp.net mvc

前端之家收集整理的这篇文章主要介绍了jQuery的ajax上传文件在asp.net mvc前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个文件在我看来
<form id="upload" enctype="multipart/form-data">
<input type="file" name="fileUpload" id="fileUpload" size="23" /><br />
</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) {}
});

但是在Request.Files中没有文件。 ajax请求有什么问题?

解决方法

Upload files using AJAX in ASP.Net MVC

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

控制器

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

编辑:HTML

<form id="uploader">
    <input id="fileInput" type="file" multiple>
    <input type="submit" value="Upload file" />
</form>
原文链接:https://www.f2er.com/jquery/185504.html

猜你在找的jQuery相关文章