ASP.NET MVC3 AJAX 上傳圖片示例


  最近在博問中看到一個問題,問在MVC中如何用AJAX方式上傳圖片,這里做了一個DEMO,詳細解釋一下。

  本DEMO代碼非常簡單,就是一個頁面上有一個上傳圖片按鈕,點擊后彈出一個層,在這個彈出層里上傳圖片,然后把圖片地址更新到頁面上。在獲得上傳的圖片地址后你可以做其他處理(如插入到文本編輯器中)。

Controller

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

    [HttpPost]
    public JsonResult Upload(HttpPostedFileBase upImg)
    {
        string fileName = System.IO.Path.GetFileName(upImg.FileName);
        string filePhysicalPath = Server.MapPath("~/upload/" + fileName);
        string pic="", error="";
        try
        {
            upImg.SaveAs(filePhysicalPath);
            pic = "/upload/" + fileName;
        }
        catch (Exception ex)
        {
            error = ex.Message;
        }
        return Json(new
        {
            pic = pic,
            error = error
        });
    }
}

  提示:這里上傳到網站根目錄的upload文件夾中,請根據自己的需要更改或添加這個目錄。

View

Index.cshtml:

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@section HeadCss{
    <style type="text/css">
        form{
            border:1px solid #CCC;
            border-radius:5px;
            padding:10px;
            margin:10px 0;
            width:400px;
            background:#EEE;
        }
    </style>
}
@section HeadScript{
    <script src="/Scripts/jquery.form.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#btn_show").bind("click", function () {
                $("#form_upload").show();
                var options = {
                    success: function (responseText, statusText, xhr, $form) {
                        var picPath = responseText.pic;
                        if (picPath == "") {
                            alert(responseText.error);
                        }
                        else {
                            $("#form_upload").hide();
                            $("#result").attr("src", picPath).show();
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.log(textStatus);
                        console.log(errorThrown);
                    }
                };

                $("#form_upload").ajaxForm(options);
            });
        });
    </script>
}
<input type="button" id="btn_show" value="上傳圖片" /><br />
<form id="form_upload" style="padding:20px; display:none;" action="upload" method="post" enctype="multipart/form-data">
    <input name="upImg" style="width:350px;height:25px;" size="38" type="file"/><input type="submit" value="上傳"/>
</form>
<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.form.js,這是一個jquery Form 插件,地址:http://jquery.malsup.com/form/

效果

打開頁面,點擊“上傳圖片”后選擇一張圖片

 

上傳后效果圖

  PS:本文只是簡單的示例,很多細節沒有處理,請使用者自己根據需要完善


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM