欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ASP.NET?MVC使用JSAjaxFileUploader插件實(shí)現(xiàn)單文件上傳

 更新時(shí)間:2022年09月11日 12:00:18   作者:Darren?Ji  
這篇文章介紹了ASP.NET?MVC使用JSAjaxFileUploader插件實(shí)現(xiàn)單文件上傳的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

先看效果:

  • 上傳文件顯示進(jìn)度條:

  • 停止上傳按鈕和關(guān)閉縮略圖按鈕:

  • 限制上傳文件的類型:

  • 限制上傳文件的尺寸:

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

  • 點(diǎn)擊界面上的刪除按鈕,界面刪除,同步刪除文件夾中文件。
  • 重新上傳文件,界面刪除,同步刪除文件夾中文件,并界面顯示新的縮略圖、文件名等。

HomeController

由于需要把保存到文件夾文件的路徑、文件名等回傳給界面,所以需要一個(gè)類,專門負(fù)責(zé)回傳給客戶端所需要的信息。

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

把上傳的文件名改成以時(shí)間命名的格式,并保存到文件夾,再把回傳信息以json形式傳遞給視圖。關(guān)于刪除,需要接收來自視圖的文件名參數(shù)。

        #region 上傳單個(gè)文件
 
        //顯示
        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>
        /// 檢查是否要?jiǎng)?chuàng)建上傳文件夾,如果沒有就創(chuàng)建
        /// </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;
        }
 
        //根據(jù)文件名稱刪除文件
        [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

前臺(tái)視圖主要做如下幾件事:

  • 每次上傳之前檢查表格中是否有數(shù)據(jù),如果有,實(shí)施界面刪除并同步刪除文件夾中的文件
  • 上傳成功動(dòng)態(tài)創(chuàng)建表格行顯示縮略圖、文件名和刪除按鈕
  • 點(diǎn)擊刪除按鈕實(shí)施界面刪除并同步刪除文件夾中的文件

由于表格行是動(dòng)態(tài)生成的,需要對刪除按鈕以"冒泡"的方式注冊事件: $('#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="external nofollow"  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字節(jié)
                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);
                }
            });
 
            //點(diǎn)擊刪除鏈接刪除剛上傳圖片
            $('#tbl').on("click", ".delImg", function () {
                deleteImg();
                //window.location.reload();
            });
        });
 
        //刪除圖片方法:點(diǎn)擊刪除鏈接或上傳新圖片刪除原先圖片用到
        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("出錯(cuò)了 '" + jqXhr.status + "' (狀態(tài): '" + textStatus + "', 錯(cuò)誤為: '" + errorThrown + "')");
                }
            });
        }
 
        //創(chuàng)建表格
        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>

另外:需要?jiǎng)h除源js文件中input元素的multiple屬性,使之只能接收單個(gè)文件。

本篇源碼在github

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接

相關(guān)文章

最新評論