天天看點

MVC——無重新整理上傳圖檔

jquery.form.js 無重新整理上傳

控制器

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Gzh.MvcWeb.Controllers
{
    public class UploadController : Controller
    {
        // GET: Upload
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 處理單張圖檔上傳
        /// </summary>
        /// <param name="upImg"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UploadImage(HttpPostedFileBase upImg)
        {
            string pic = "", error = "";
            try
            {
                if (upImg != null)
                {
                    string fileName = System.IO.Path.GetFileName(upImg.FileName); //擷取上傳的檔案名
                    string fileExt = Path.GetExtension(fileName);//擷取擴充名

                    if (Exist(fileExt))
                    {
                        string virtualPath;
                        string filePath;
                        PerSave(fileName, out virtualPath, out filePath);
                        upImg.SaveAs(filePath);
                        pic = virtualPath;
                    }
                    else
                    {
                        error = "格式不正确";
                    }
                }
                else
                {
                    error = "請選擇圖檔";
                }
            }
            catch (Exception e)
            {
                 //log
                error = "程式出錯";
            }

            return Json(new
            {
                pic = pic,
                error = error
            });
        }

        /// <summary>
        /// 預上傳,生産檔案儲存的真實路徑和虛拟路徑
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="virtualPath"></param>
        /// <param name="filePath"></param>
        private void PerSave(string fileName, out string virtualPath, out string filePath)
        {
            string datafolder = "/upload/" + DateTime.Now.Year.ToString() + ("0" + DateTime.Now.Month.ToString()).Substring(("0" + DateTime.Now.Month.ToString()).Length - , ) + "/"; //檔案夾
            string newFileName = DateTime.Now.Ticks.ToString() + "_" + fileName;  //新的檔案名
            virtualPath = datafolder + newFileName; //虛拟路徑
            filePath = Server.MapPath(virtualPath); //檔案儲存的位址

            if (!Directory.Exists(Path.GetDirectoryName(filePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            }
        }


        /// <summary>
        /// 判斷字尾
        /// </summary>
        /// <param name="ext"></param>
        /// <returns></returns>
        private bool Exist(string ext)
        {
            bool b = false;
            ArrayList list = new ArrayList() { ".jpeg", ".jpg", ".png", ".gif" };
            if (list.Contains(ext))
            {
                b = true;
            }

            return b;

        }

    }
}
           

前端代碼

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>mvc 無重新整理 上傳圖檔</title>
    <style type="text/css">
        form {
            border: px solid #CCC;
            border-radius: px;
            padding: px;
            margin: px ;
            width: px;
            background: #EEE;
        }
    </style>
</head>
<body>
    <h1>mvc 無重新整理 上傳單張圖檔</h1>
    <form id="form_upload" action="/Upload/UploadImage" method="post" enctype="multipart/form-data">
        <input name="upImg" type="file" /><input type="submit" value="上傳" />
    </form>
    <img alt="" style="display:none;" id="result" src="" />

</body>
</html>


<script src="~/Scripts/jquery-2.1.3.min.js"></script>
<script src="~/Scripts/jquery.form.js"></script>
<script type="text/javascript">
    $(function () {
        var options = {
            success: function (responseText, statusText, xhr, $form) {
                var picPath = responseText.pic;
                if (picPath == "") {
                    alert(responseText.error);
                }
                else {
                    $("#result").attr("src", picPath).show();
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(textStatus);
                console.log(errorThrown);
            }
        };

        $("#form_upload").ajaxForm(options);
    });
</script>

           

效果 (上傳時候頁面并不會重新整理)

MVC——無重新整理上傳圖檔
MVC——無重新整理上傳圖檔

繼續閱讀