bootstrap-fileinput上傳外掛試用

Mr-Wanter發表於2017-07-28

0、效果圖


1、引入js、css(建議css放在html頭部,js載入在html底部)

<link href="~/Content/fileinput.min.css" rel="stylesheet" />

<script src="~/scripts/jquery-1.10.2.min.js"></script>
<script src="~/scripts/fileinput.js"></script>
<script src="~/scripts/zh.js"></script>

2、html

  <input type="file" id="uploaddoc" name="file" class="file" multiple />//上傳按鈕 multiple為可多檔案上傳
  <input type="hidden" id="Doc" name="doc" value="" />//儲存檔案路徑
3、初始化

 $("#uploaddoc").fileinput({
        language: 'zh',
        uploadUrl: '/Form/upload',//後臺上傳方法
        allowedFileExtensions: ['doc', 'docx'],//上傳副檔名
        shouUpload: false,
        showRemove: false,
        browseClass: 'btn btn-danger',
        maxFileSize: 5000,
        maxFileNum: 10,
        allowedPreviewTypes: null,
        previewFileIconSettings: {
            'doc': '<i class="fa fa-file-word-o text-muted"></i>'
        },
        previewFileExtSettings: {
            'doc': function (ext) {
                return ext.match(/(doc|docx)$/i);
            }
        }
    });
4、回撥方法

 var List = new Array();//宣告儲存上傳檔案路徑陣列物件
    //上傳 - 刪除
    $('#uploaddoc').on('filesuccessremove', function (event, key) {
        var abort = true;
        if (confirm("確定要刪除已上傳的檔案嗎?")) {
            abort = false;
        }
        var index1;
        $.each(List, function (index, item) {
            if (item.KeyID == key) {//預設fileinput.js的key與KeyID不一致,需要改動原始碼,詳情見下文
                index1 = index;
                $.post("/Form/uploaddelete", { key: item.KeyID, path: item.path });//刪除以上傳到本地的檔案
            }
        });
        List.splice(index1, 1);
        var path = "";
        $.each(List, function (index, item) {
            path += item.path;
        });
        $("#Doc").val(path);//修改儲存的檔案路徑
    });
    //取消上傳事件,左上角的取消按鈕
    $('#uploaddoc').on('filecleared', function (event, files) {
        $.each(List, function (index, item) {
            $.post("/Form/uploaddelete", { key: "all", path: item.path });
        });
        List = new Array();//清空儲存的檔案路徑陣列物件,這裡是賦值給新的空物件,應該可以優化為刪除以儲存的所有值
        $("#Doc").val("");
    });

    //上傳 - 成功
    $("#uploaddoc").on("fileuploaded", function (event, data, previewId, index) {
        var form = data.form, files = data.files, extra = data.extra,
         response = data.response, reader = data.reader;
        List.push({ path: response.path, KeyID: previewId })
        $("#Doc").val($("#Doc").val() + response.path);
        //$("#Doc").val(List);
    });


5、後臺上傳方法

//上傳方法  
public JsonResult Upload()
        {
            HttpPostedFileBase file = Request.Files["file"];
            if (file == null)
            {
                return Json(new { error = "上傳異常" });
            }
            var ext = Path.GetExtension(file.FileName);
            var filename = Path.GetFileNameWithoutExtension(file.FileName);
            var serverfilenname = Guid.NewGuid().ToString("n") + "_" + filename + ext;
            try
            {
                var path = "/File";
                var dic = string.Format("{0}/{1}/{2}/{3}", path, DateTime.Today.Year.ToString(), DateTime.Today.Month.ToString(), DateTime.Today.Day.ToString());
                if (!Directory.Exists(Server.MapPath(dic)))
                {
                    Directory.CreateDirectory(Server.MapPath(dic));
                }
                var webpath = string.Format("{0}/{1}", dic, serverfilenname);
                var serverpath = Path.Combine(Server.MapPath(dic), serverfilenname);
                
                file.SaveAs(serverpath);
                return Json(new {
                    url = "/Form/uploaddelete",//定義要刪除的action,沒有用到可刪掉
                    key = serverfilenname,
                    path = webpath });
            }
            catch (Exception ex)
            {
                return Json(new { error = "上傳異常" + ex });
            }
        }
//刪除本地檔案方法
public JsonResult UpLoadDelete()
        {
            try
            {
                var key = Request.Params["key"];
                var path = Request.Params["path"];
                if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(path))
                {
                    return Json(false, JsonRequestBehavior.DenyGet);
                }
                path = Server.MapPath(path);
                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                    return Json(true, JsonRequestBehavior.DenyGet);
                }
                else
                {
                    return Json(false, JsonRequestBehavior.DenyGet);
                }
            }
            catch (Exception)
            {
                return Json(false, JsonRequestBehavior.DenyGet);
            }
        }
6、缺點

尚未研究預覽功能

尚有優化空間

7、說明

程式碼貼上後可直接使用,後臺框架為.net mvc5,預設母版頁有載入bootstrap樣式和js 如無樣式請新增對bootstrap的指令碼引用

外掛api地址:http://plugins.krajee.com/file-input#events  

上網查了好多相關資料 都不完整,最後只有這個api可以看了,最後終於找到左上角關閉按鈕的回撥事件

參考部落格地址:

http://blog.csdn.net/xumoqiu/article/details/53081352?locationNum=1&fps=1

https://izk.cloud/463/







相關文章