【.NET】基於MVC的layui文件上傳與接收

1、目的需求:前臺批量上傳文件,並在後臺進行接收

前臺代碼:配置URL路徑: url: '/KeepElectricty/uploadfiles'其中KeepElectricty是控制器,uploadfiles是接收方法

<!--HTML部分-->
 <div class="layui-upload" style="margin:10px;margin-left: 30px;">
        <button type="button" class="layui-btn layui-btn-normal" id="testList">選擇多文件</button>
        <div class="layui-upload-list">
            <table class="layui-table" id="fileTable">
                <thead>
                    <tr>
                        <th>文件名</th>
                        <th>大小</th>
                        <th>狀態</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="demoList"></tbody>
            </table>
        </div>
        <button type="button" class="layui-btn" id="testListAction">開始上傳</button>
    </div>
<script>

    init();
 function init() {
        $("#testListAction").hide();
        $("#fileTable").hide();

        layui.use('upload', function () {
            var $ = layui.jquery
                , upload = layui.upload;


            //多文件列表示例
            var demoListView = $('#demoList')
                , uploadListIns = upload.render({
                    elem: '#testList'
                    , url: '/KeepElectricty/UploadFiles'
                    , accept: 'file'
                    , multiple: true
                    , auto: false
                    , bindAction: '#testListAction'
                    , choose: function (obj) {
                        $("#testListAction").show();
                        $("#fileTable").show();

                        var files = this.files = obj.pushFile(); //將每次選擇的文件追加到文件隊列
                        //讀取本地文件
                        obj.preview(function (index, file, result) {
                            var tr = $(['<tr id="upload-' + index + '">'
                                , '<td>' + file.name + '</td>'
                                , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                                , '<td>等待上傳</td>'
                                , '<td>'
                                , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">刪除</button>'
                                , '</td>'
                                , '</tr>'].join(''));

                            //單個重傳
                            tr.find('.demo-reload').on('click', function () {
                                obj.upload(index, file);
                            });

                            //刪除
                            tr.find('.demo-delete').on('click', function () {
                                delete files[index]; //刪除對應的文件
                                tr.remove();
                                uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免刪除後出現同名文件不可選
                            });

                            demoListView.append(tr);
                        });
                    }
                    , done: function (res, index, upload) {
                        if (res.code == 200) { //上傳成功
                            var tr = demoListView.find('tr#upload-' + index)
                                , tds = tr.children();
                            tds.eq(2).html('<span style="color: #5FB878;">上傳成功</span>');
                            tds.eq(3).html(''); //清空操作
                            return delete this.files[index]; //刪除文件隊列已經上傳成功的文件
                        } else if (res.code == 500) {
                            this.error(index, upload);
                        } else if (res.code == 403) {
                            layui.use('layer', function () {
                                layer = layui.layer;
                                layer.msg('上傳時發生致命錯誤!', {
                                    icon: 2
                                });
                            });
                        }
                        
                    }
                    , error: function (index, upload) {
                        var tr = demoListView.find('tr#upload-' + index)
                            , tds = tr.children();
                        tds.eq(2).html('<span style="color: #FF5722;">上傳失敗</span>');
                        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //顯示重傳
                    }
                });
        });

    }
</script>

後臺接收代碼:

public ActionResult UploadFiles()
        {

            string path = "~/Pageconfig/map/tiles/baodianFiles/";
            try
            {
                var file = Request.Files[0]; //獲取選中文件  
                var filecombin = file.FileName.Split('.');
                if (file == null || String.IsNullOrEmpty(file.FileName) || file.ContentLength == 0 || filecombin.Length < 2)
                {
                    return Json(new  {  msg = "上傳出錯", code = 500});
                }
                //定義本地路徑位置
                string local = path.Replace("~/","").Replace('/','\\');
             
                string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, local);
                 
                var saveName = file.FileName;
                var tmpIndex = 0;
                //判斷是否存在相同文件名的文件 相同累加1繼續判斷
                while (System.IO.File.Exists(Server.MapPath(path) + saveName))
                {
                    saveName = filecombin[0] + "_" + ++tmpIndex + "." + filecombin[1];
                }
 

                if (!System.IO.Directory.Exists(localPath))
                    System.IO.Directory.CreateDirectory(localPath);
                string localURL = Path.Combine(local, saveName);


                file.SaveAs(Path.Combine(localPath, saveName));   //保存文件   
                return Json(new {  msg = "上傳成功", code = 200 });

            }  catch {
                return Json(new { msg = "上傳異常", code = 403 });
            }
          
        }

以下是調試:

A:選擇文件

B:點擊上傳

C:進行DEBUG調試

此時通過監視發現文件已經上傳過來。

D:驗證文件夾下是否已經存儲

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章