asp.net MVC中的jQuery Ajax上传文件

asp.net MVC中的jQuery Ajax上传文件,第1张

asp.net MVC中的jQuery Ajax上传文件

在ASP.Net MVC中使用AJAX上传文件

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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5050308.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-15

发表评论

登录后才能评论

评论列表(0条)

保存