Mvc之Ajax上传图片

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

  

posted @ 2016-05-27 15:34  成败在我手  阅读(1329)  评论(0编辑  收藏  举报