ASP.NET MVC3 AJAX 上传图片示例

最近在博问中看到一个问题,问在MVC中如何用AJAX方式上传图片,这里做了一个DEMO,详细解释一下。

  本DEMO代码非常简单,就是一个页面上有一个上传图片按钮,点击后弹出一个层,在这个弹出层里上传图片,然后把图片地址更新到页面上。在获得上传的图片地址后你可以做其他处理(如插入到文本编辑器中)。

Controller

public class ImageController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public void Upload(HttpPostedFileBase upImg)
    {
        string fileName = System.IO.Path.GetFileName(upImg.FileName);
        string filePhysicalPath = Server.MapPath("~/upload/" + fileName);
        string picPath = "{}";
        try
        {
            upImg.SaveAs(filePhysicalPath);
            picPath = string.Format("{{\"pic\":\"{0}\"}}", "/upload/" + fileName);
        }
        catch (Exception ex)
        {
            picPath = "{\"pic\":\"\",\"error\":\"" + ex.Message + "\"}";
        }
        this.HttpContext.Response.Write(picPath);
    }
}

  提示:这里上传到网站根目录的upload文件夹中,请根据自己的需要更改或添加这个目录。

View

Index.cshtml:

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@section HeadCss{
}
@section HeadScript{
    <script src="/Scripts/jquery.artwl.thickbox.js" type="text/javascript"></script>
    <script src="/Scripts/jquery.form.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#btn_show").bind("click", function () {
                var uploadHtml = $('<form id="form_upload" style="padding:20px;" action="/Image/upload" method="post" enctype="multipart/form-data">\
                <input name="upImg" style="width:350px;height:25px;" size="38" type="file"/><input type="submit" value="上传"/>\
                </form>');

                var options = {
                    dataType: "json",
                    success: function (responseText, statusText, xhr, $form) {
                        var picPath = responseText.pic;
                        if (picPath == "") {
                            alert(responseText.error);
                        }
                        else {
                            $.artwl_close();
                            $("#result").attr("src", picPath).show();
                        }
                    },
                    error: function () {
                        alert("error");
                    }
                };

                $.artwl_bind({ title: "上传图片", content: uploadHtml, callback: function () {
                    $("#form_upload").ajaxForm(options);
                }
                });
            });
        });
    </script>
}
<input type="button" id="btn_show" value="上传图片" /><br />
<img alt="" style="display:none;" id="result" src="" />

  提示:在options的success方法中获取到上传的图片地址,你可以根据需要进行后续处理

_Layout.cshtml:

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    @RenderSection("HeadCss",required:false)
    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
    @RenderSection("HeadScript",required:false)
</head>
<body>
    @RenderBody()
</body>
</html>

引用的几个文件

Site.css跟jquery-1.4.4.min.js就不说了,用VS创建MVC项目默认就有

jquery.artwl.thickbox.js,这是我自己写的一个弹出层插件,具体见这里:分享一个灰常简单好用的jQuery弹出层插件:jquery.artwl.thickbox.js,(注意:本文用的是文章中插件更新部分)

jquery.form.js,这是一个jquery Form 插件,地址:http://jquery.malsup.com/form/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值