码迷,mamicode.com
首页 > Web开发 > 详细

Mvc之Ajax上传图片

时间:2016-05-27 16:15:09      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

MyAjaxForm下载地址,点击此处下载

视图部分:

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>
<form id="fm1" method="post">
    <input type="file" id="btnfile" name="btnfile" value="提交" />
    <input type="button" id="btn"  value="上传" />
</form>
<div id="divimg"></div>
@section scripts{
<script src="/scripts/MyAjaxForm.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        $("#btn").click(function () {
           // alert("ok2");
            $("#fm1").ajaxSubmit({
                url: ‘@Url.Action("Uploadfile")‘,
                type: ‘post‘,
                success: function (data) {
                    data = data.replace(‘<PRE>‘, ‘‘).replace(‘</PRE>‘, ‘‘);
                    $(‘#divimg‘).append(‘<img src="‘ + data + ‘" width="200px"  height="200px" />‘);
                    var file = $(‘#btnfile‘);
                    file.after(file.clone().val(‘‘));
                    file.remove();
                }
            });
        });
    });
</script>
}

  后台控制器部分

   public ActionResult Uploadfile() 
        {
            //上传文件
            HttpPostedFileBase img = Request.Files["btnfile"];
            string s = img.FileName;
            string fileExtension = Path.GetExtension(s);
            string path = "/Temp/"  ;
            if (Directory.Exists(Server.MapPath(path)) == false)//如果不存在就创建file文件夹
            {
                Directory.CreateDirectory(Server.MapPath(path));
            }
            string virpath = path + Guid.NewGuid() + fileExtension ;

            img.SaveAs(Server.MapPath(virpath));
            return Content(virpath);
        }

  

Mvc之Ajax上传图片

标签:

原文地址:http://www.cnblogs.com/bubugao/p/MyAjaxForm.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!