(MVC)jquery+ajax上传文件

来源:互联网 发布:全球人工智能发展趋势 编辑:程序博客网 时间:2024/05/22 16:36

1. View页面代码

  <script src="~/***/jquery-form.js"></script>  <form id="filePost" action="/Home/Upload" method="post" enctype="multipart/form-data">  <label> Filename: <input type="file" name="file" onchange="save();" /></label>  <input id="ButtonUpload" type="submit" value="Upload" />  </form>  <div id="outputdiv"></div>


2.Controller页面 

        public JsonResult Upload(HttpPostedFileBase file)        {            if (file.ContentLength == 0)            {                return Json(new                {                    bRet = false,                    sMsg = "请选择图片!"                }, "text/html");            }            //上传文件代码 记得先新建一下 Upload 文件夹            var fileName = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(file.FileName));            try            {                file.SaveAs(fileName);                return Json(new                {                    bRet = true,                    sMsg = "上传成功"                }, "text/html");            }            catch (Exception ex)            {                _log.Error(ex.Message);                return null;            }       }


3.javascript

 <script>        function save() {            var options = {                            beforeSubmit: showRequest,                error: showError,                success: showResponse            };            $('#filePost').ajaxSubmit(options);        }        $(document).ready(function () {            var options = {                target: '#outputdiv',                beforeSubmit: showRequest,                error: showError,                success: showResponse            };            $('#filePost').submit(function () {                $(this).ajaxSubmit(options);                return false;            });        });        function showRequest(formData, jqForm, options) {            alert('发送前');            return true;        }        function showError(data) {            alert('error');        }        function showResponse(responseText, statusText) {            alert(responseText + "," + statusText + "," + '发送后');    </script>

4 jquery.form.js 下载

http://download.csdn.net/detail/zerorm/9550174

0 0
原创粉丝点击