MVC文件圖片ajax上傳輕量級解決方案,使用客戶端JSAjaxFileUploader插件01-單文件上傳


前段時間做了幾個關於圖片、文件上傳的Demo,使用客戶端Query-File-Upload插件和服務端Badkload組件實現多文件異步上傳,比如"MVC文件上傳04-使用客戶端jQuery-File-Upload插件和服務端Backload組件實現多文件異步上傳",就Demo而言,效果還算不錯,但到了實際項目,發現使用Query-File-Upload插件和服務端Badkload組件與項目比較難融合,有"重"的感覺。相比而言,JSAjaxFileUploader這款插件比較"輕量級",它可以幫我們實現單個文件或多個文件的異步上傳和管理,並且有不錯的客戶端效果,它的Demo在這里

 

本篇源碼在github,先看效果:

● 上傳文件顯示進度條:

上傳進度條

 

● 停止上傳按鈕和關閉縮略圖按鈕:

右上角有停止上傳和關閉按鈕

 

● 限制上傳文件的類型:

文件類型不支持

 

● 限制上傳文件的尺寸:

限制上傳文件尺寸

 

●上傳成功后顯示縮略圖、文件名以及回傳信息:

上傳成功顯示縮略圖文件名和刪除鏈接

● 點擊界面上的刪除按鈕,界面刪除,同步刪除文件夾中文件。
● 重新上傳文件,界面刪除,同步刪除文件夾中文件,並界面顯示新的縮略圖、文件名等。

 

□ HomeController

由於需要把保存到文件夾文件的路徑、文件名等回傳給界面,所以需要一個類,專門負責回傳給客戶端所需要的信息。

    public class UploadFileResult
    {
        public string FileName { get; set; }
        public int Length { get; set; }
        public string Type { get; set; }
        public bool IsValid { get; set; }
        public string Message { get; set; }
        public string FilePath { get; set; } 
    }

把上傳的文件名改成以時間命名的格式,並保存到文件夾,再把回傳信息以json形式傳遞給視圖。關於刪除,需要接收來自視圖的文件名參數。

        #region 上傳單個文件
 
        //顯示
        public ActionResult Index()
        {
            return View();
        }
 
        //接收上傳
        [HttpPost]
        public ActionResult UploadFile()
        {
            List<UploadFileResult> results = new List<UploadFileResult>();
            foreach (string file in Request.Files)
            {
                HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                if (hpf.ContentLength == 0 || hpf == null)
                {
                    continue;
                }
 
                var fileName = DateTime.Now.ToString("yyyyMMddhhmmss") +
                               hpf.FileName.Substring(hpf.FileName.LastIndexOf('.'));
                string pathForSaving = Server.MapPath("~/AjaxUpload");
                if (this.CreateFolderIfNeeded(pathForSaving))
                {
                    hpf.SaveAs(Path.Combine(pathForSaving, fileName));
                    results.Add(new UploadFileResult()
                    {
                        FilePath = Url.Content(String.Format("~/AjaxUpload/{0}", fileName)),
                        FileName = fileName,
                        IsValid = true,
                        Length = hpf.ContentLength,
                        Message = "上傳成功",
                        Type = hpf.ContentType
                    });
                }
            }
 
            return Json(new
            {
                name = results[0].FileName,
                type = results[0].Type,
                size = string.Format("{0} bytes", results[0].Length),
                path = results[0].FilePath,
                msg = results[0].Message
            });
        }    
 
        #region 共用方法
        /// <summary>
        /// 檢查是否要創建上傳文件夾,如果沒有就創建
        /// </summary>
        /// <param name="path">路徑</param>
        /// <returns></returns>
        private bool CreateFolderIfNeeded(string path)
        {
            bool result = true;
            if (!Directory.Exists(path))
            {
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception)
                {
                    //TODO:處理異常
                    result = false;
                }
            }
            return result;
        }
 
        //根據文件名稱刪除文件
        [HttpPost]
        public ActionResult DeleteFileByName(string name)
        {
            string pathForSaving = Server.MapPath("~/AjaxUpload");
            System.IO.File.Delete(Path.Combine(pathForSaving, name));
            return Json(new
            {
                msg = true
            });
        }
        #endregion        
 

□ Home/Index.cshml

前台視圖主要做如下幾件事:
● 每次上傳之前檢查表格中是否有數據,如果有,實施界面刪除並同步刪除文件夾中的文件
● 上傳成功動態創建表格行顯示縮略圖、文件名和刪除按鈕
● 點擊刪除按鈕實施界面刪除並同步刪除文件夾中的文件

由於表格行是動態生成的,需要對刪除按鈕以"冒泡"的方式注冊事件: $('#tb').on("click", ".delImg", function ()

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link href="~/Content/JSAjaxFileUploader/JQuery.JSAjaxFileUploader.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script src="~/Scripts/JSAjaxFileUploader/JQuery.JSAjaxFileUploaderSingle.js"></script>
    <style type="text/css">
        #tb table{
            border-collapse: collapse;              
            width: 600px;         
        }
 
        #tb td {
            text-align: center;
            padding-top: 5px;
            width: 25%;
        }
 
        #tb tr {
            background-color: #E3E3E3;
            line-height: 35px;
        }
 
        .showImg {
            width: 50px;
            height: 50px;
        }
    </style>
    <script type="text/javascript">
        $(function () {
            //隱藏顯示圖片的表格
            $('#tbl').hide();
 
            $('#testId').JSAjaxFileUploader({
                uploadUrl: '@Url.Action("UploadFile","Home")',
                inputText: '選擇上傳文件',
                //fileName: 'photo',
                maxFileSize: 512,    //Max 500 KB file 1kb=1024字節
                allowExt: 'gif|jpg|jpeg|png',
                zoomPreview: false,
                zoomWidth: 360,
                zoomHeight: 360,
                beforesend: function (file) {
                    if ($('.imgName').text() != "") {
                        deleteImg();
                        $('#tbl').hide();
                    }
                },
                success: function (data) {
                    $('.file_name').html(data.name);
                    $('.file_type').html(data.type);
                    $('.file_size').html(data.size);
                    $('.file_path').html(data.path);
                    $('.file_msg').html(data.msg);
                    createTableTr();
                    $('#tbl').show();
                    $('.showImg').attr("src", data.path);
                    $('.imgName').text(data.name);
                },
                error: function (data) {
                    alert(data.msg);
                }
            });
 
            //點擊刪除鏈接刪除剛上傳圖片
            $('#tbl').on("click", ".delImg", function () {
                deleteImg();
                //window.location.reload();
            });
        });
 
        //刪除圖片方法:點擊刪除鏈接或上傳新圖片刪除原先圖片用到
        function deleteImg() {
            $.ajax({
                cache: false,
                url: '@Url.Action("DeleteFileByName", "Home")',
                type: "POST",
                data: { name: $('.imgName').text() },
                success: function (data) {
                    if (data.msg) {
                        //alert("圖片刪除成功");
                        $('.delImg').parent().parent().remove();
                        
                    }
                },
                error: function (jqXhr, textStatus, errorThrown) {
                    alert("出錯了 '" + jqXhr.status + "' (狀態: '" + textStatus + "', 錯誤為: '" + errorThrown + "')");
                }
            });
        }
 
        //創建表格
        function createTableTr() {
            var table = $('#tbl');
            table.append("<tr><td><img class='showImg'/></td><td colspan='2'><span class='imgName'></span></td><td><a class='delImg' href='javascript:void(0)'>刪除</a></td></tr>");
        }
    </script>
</head>
<body>
    <div id="testId"></div>
    
    <div id="tb">
        <table id="tbl">
            <tbody>         
            </tbody>
        </table>
    </div>
        <div class="file_name"></div>
        <br />
        <div class="file_type"></div>
        <br />
        <div class="file_size"></div>
        <br />
        <div class="file_path"></div>
        <br />
        <div class="file_msg"></div>
</body>
</html>
 

 

另外:
需要刪除源js文件中input元素的multiple屬性,使之只能接收單個文件。


免責聲明!

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



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