javascript razor : Large File Upload


Except the backend db crud and create file by memory stream,
I post two parts of it, the first is how I resolve this by original javascript and jquery library,
and the second would be some web.config which I need to adjust.

cshtml page

@model  List<ViewModel.View_File_Mstr>
@using .Models
@using .ViewModel
@{
    Layout = "~/Views/Shared/_PageLayout.cshtml";
    ViewBag.Title = "檔案列表";
    var controller = ViewContext.RouteData.Values["controller"].ToString();
    var action = ViewContext.RouteData.Values["action"].ToString();
    Category_Sql Category_Sql = new Category_Sql();
    View_Collection_Mstr_Sql View_Collection_Mstr_Sql = new View_Collection_Mstr_Sql();
    Academic_Year_Sql Academic_Year_Sql = new Academic_Year_Sql();
}

<style>
    .class_td_pictures {
        white-space: pre-wrap !important;
        max-width: 200px;
    }

    .class_td_description {
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        max-width: 50px;
    }
        .class_td_displayName {
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        max-width: 100px;
    }
        .class_td_file_no{
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        max-width: 110px;
        }
        .class_td_action{
        white-space: nowrap;
        /*text-overflow: ellipsis;*/
        overflow: hidden;
        max-width: 170px;
        }
        .class_td_version {
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        /*max-width: 50px;*/
        width:10px;
    }
        .class_td_active{
        white-space: nowrap;
        /*text-overflow: ellipsis;*/
        overflow: hidden;
        max-width: 50px;
        width:28px;
    }
        .class_td_collection{
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        max-width: 55px;
    }
    .class_td_uploadTime {
        /*word-wrap:break-word;*/
        /*white-space: nowrap;*/
        /*text-overflow: ellipsis;*/
        /*overflow: hidden;*/
        /*max-width: 120px;*/
        width:10px;
    }

    .card .card-header {
        padding: 0px 20px 20px 20px;
        display: flex;
        justify-content: space-between;
        /*justify-content: flex-end;*/
    }

    .my_select_size {
        margin: 10px;
        width: 80%;
    }

    .my_div_label_and_select {
        display: flex;
        align-items: center;
        /*width:25%;*/
        width:40%;
    }
    /*slider size controll*/

.switch {
  position: relative;
  display: inline-block;
  width: 30px;
  height: 17px;
}

.switch input { 
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 13px;
  width: 13px;
  left: 2px;
  bottom: 2px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(13px);
  -ms-transform: translateX(13px);
  transform: translateX(13px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
</style>
<div class="card">
    <div class="card-header">
        <div class="my_div_label_and_select">
            @Html.DropDownList("category_id", Category_Sql.Get_GropDownList_For_Category(), "全類別", new { @class = "form-control my_select_size" })
            @Html.DropDownList("academic_year_id", Academic_Year_Sql.Get_GropDownList_For_Academic_Year(), "全學年度", new { @class = "form-control my_select_size" })
            @Html.DropDownList("collection_id", View_Collection_Mstr_Sql.Get_GropDownList_For_Collection(), "全系列", new { @class = "form-control my_select_size" })
        </div>
        <div>
            <h3 id="alert_phrase" style="margin-right:105.781px;margin-top: 10px"></h3>
        </div>
        <div>
            <a class="btn btn-primary" style="color:white;margin:10px;" onclick="run_upload_list()">批量上傳</a>
            @*<a class="btn btn-primary" style="color:white;margin:10px;" data-toggle="modal" data-target="#modal-main" @*href="@Url.Action("Sort","Academic_Year")">排序</a>*@
            <a class="btn btn-primary" style="color:white;margin:10px;" href="@Url.Action("Create","File")">新增</a>
            @*<a class="btn btn-primary" style="color:white;margin:10px;" href="@Url.Action("export_excel","DataTable")">當前Excel匯出</a>
                <a class="btn btn-primary" style="color:white;margin:10px;" href="@Url.Action("import_excel_multiple_insert","DataTable")">Excel批量新增</a>
                <a class="btn btn-primary" style="color:white;margin:10px;" href="@Url.Action("import_excel_multiple_update","DataTable")">Excel批量更新</a>*@
        </div>
    </div>
    <div class="card-block">
        <!---datatable----------------------------------------------------------------->
        <div class="dt-responsive table-responsive" id="div_data_table">
            <table class="table table-striped table-bordered nowrap" style="width:100%" id="datatable">
                <thead class="thead-default thead-lg">
                    <tr>
                        <th>顯示名稱</th>
                        <th>類別</th>
                        <th>檔案名稱</th>
                        <th>檔案大小</th>
                        <th>綁定系列</th>
                        <th>網頁</th>
                        <th>PC</th>
                        <th>上傳狀態</th>
                        <th>版本</th>
                        <th>上傳時間</th>
                        <th>操作</th>
                    </tr>
                </thead>
                @*<tbody>
                    @foreach (var item in Model)
                    {
                        <tr>
                            <td>@item.file_chi_display</td>
                            <td>類別</td>
                            <td>@item.file_no</td>
                            <td>@item.file_size</td>
                            <td>查看</td>
                            <td>
                                <label class="switch">
                                    @if (item.active == true)
                                    {
                                        <input onclick="active_toggle(this, '@item.id')" type="checkbox" name="active" checked>
                                    }
                                    else
                                    {
                                        <input onclick="active_toggle(this,'@item.id')" type="checkbox" name="active">
                                    }
                                    <span class="slider round"></span>
                                </label>
                            </td>
                            <td>@item.upload_status</td>
                            <td>@item.version</td>
                            <td>@item.upload_time</td>
                            <td>
                                <a href="@Url.Action("Modify","Academic_Year",new { id=item.id})">編輯</a>
                            </td>
                        </tr>
                    }
                </tbody>*@
            </table>
        </div>
    </div>
</div>
<div id="upload_id_hidden" value="" hidden></div>

<script type="text/javascript">
    $(function () {

        //回到紀錄的搜尋條件和頁面
        //每頁筆數
        let length_value = parseInt(sessionStorage.getItem("@controller" + "-" + "@action" + "-pageLength"));
        let pageLength = Number.isNaN(length_value) ? 10 : length_value;


        //搜尋條件-類別
        let search_category_key = "@controller" + "-" + "@action" + "-category_id";
        if (!isEmpty(sessionStorage.getItem(search_category_key))) {
            let search_category_val = sessionStorage.getItem(search_category_key).toString();
            $('#category_id').val(search_category_val).change();
        }


        //搭配條件-學年度
        let search_year_key="@controller" + "-" + "@action" + "-academic_year_id";
        if (!isEmpty(sessionStorage.getItem(search_year_key))) {
            let search_year_val = sessionStorage.getItem(search_year_key).toString();
            $("#academic_year_id").val(search_year_val).change();
        } else {
            //清空系列
            $("#collection_id").empty();
            $("#collection_id").append(`<option value="">全系列</option>`);
            //清空系列紀錄
            clear_search_collection();
        }

        //搜尋條件-系列
        let search_collection_key = "@controller" + "-" + "@action" + "-collection_id";
        if (!isEmpty(sessionStorage.getItem(search_collection_key))) {
            let search_collection_val = sessionStorage.getItem(search_collection_key).toString();
            $("#collection_id").val(search_collection_val).change();
        }

        let pageKey = "@controller" + "-" + "@action" + "-pageIndex";
        let page_value = parseInt(sessionStorage.getItem(pageKey));
        let pageIndex = Number.isNaN(page_value) ? 0 : page_value;
        let displayStart = pageIndex * pageLength;

        //<!--------------------------dataTable-------------------------->
        var table = $('#datatable').DataTable({
            pageLength: pageLength,
            bAutowidth: false,
            columnDefs: [
            {
                "searchable": true,
                "orderable": true,
                "className":"class_td_displayName",
                "targets": 0
            },
            {
                "searchable": false,
                "orderable": true,
                "className":"class_td_displayName",
                "targets": 1
            },
            {
                "searchable": false,
                "orderable": true,
                "className": "class_td_file_no",
                "targets": 2
            },
            {
                "searchable": false,
                "orderable": true,
                "className": "",
                "targets": 3
            },
            {
                "searchable": false,
                "orderable": false,
                "className": "class_td_collection",
                "targets": 4
            }
            , {
                "searchable": false,
                "orderable": false,
                "className": "class_td_active",
                "targets": 5
            }
            , {
                "searchable": false,
                "orderable": false,
                "className": "class_td_active",
                "targets": 6
            }
            , {
                "searchable": false,
                "orderable": true,
                "className": "class_td_pictures",
                "targets": 7
            }
            , {
                "searchable": false,
                "orderable": false,
                "className": "class_td_version",
                "targets": 8
            }
            , {
                "searchable": false,
                "orderable": true,
                "className": "class_td_uploadTime",
                "targets": 9
            }
            , {
                "searchable": false,
                "orderable": false,
                "className": "class_td_action",
                "targets": 10
            }
            ],
            "processing": true,
            "serverSide": true,
            "displayStart": displayStart,
            "columns": [
                {
                    "data": function (source, type, val) {
                        let html = `<span title="${source.file_chi_display}">${source.file_chi_display}</span>`;
                        return html;

                    }, "name": "file_chi_display"
                },
                {
                    "data": function (source, type, val) {
                        if (isEmpty(source.category_chi)) return `<span title=""></span>`;
                        let html = `<span title="${source.category_chi}">${source.category_chi}</span>`
                        return html;

                    }, "name": "category_chi"
                },
                {
                    "data": function (source, type, val) {
                        if (isEmpty(source.file_no))
                            return `<span id="file_no${source.id}"></span>`;
                        let html = `<span id="file_no${source.id}">${source.file_no}</span>`;
                        return html;
                    }, "name": "file_no"
                },
                {
                    "data": function (source, type, val) {
                        if(isEmpty(source.file_size))
                            return `<span id="file_size${source.id}"></span>`;
                    let html = `<span id="file_size${source.id}">${source.file_size}</span>`;
                    return html;
                    }, "name": "file_size"
                },
                {
                    "data": function (source, type, val) {
                        let collection_read_href = "@Url.Action("Collection_Read","File")" + "?id=" + source.id;
                        let html = `<a href="${collection_read_href}" data-toggle="modal" data-target="#modal-main" style="color:#3498DB">查看</a>`;
                        return html;
                    }
                },
                {
                    "data": function (source, type, val) {
                        let active_col = `<label class="switch">`;

                        if (source.is_web == true) {
                            active_col += `<input onclick="isWeb_toggle(this, ${source.id})" type="checkbox" name="active" checked>`;
                        }
                        else {
                            active_col += `<input onclick="isWeb_toggle(this,${source.id})" type="checkbox" name="active">`;
                        }
                        active_col += `<span class="slider round"></span></label>`;
                        return active_col;
                    }
                },
                {
                    "data": function (source, type, val) {
                        let active_col = `<label class="switch">`;

                        if (source.is_pc == true) {
                            active_col += `<input onclick="isApp_toggle(this, ${source.id})" type="checkbox" name="active" checked>`;
                        }
                        else {
                            active_col += `<input onclick="isApp_toggle(this,${source.id})" type="checkbox" name="active">`;
                        }
                        active_col += `<span class="slider round"></span></label>`;
                        return active_col;
                    }
                },
                {
                    "data": function (source, type, val) {
                        if (isEmpty(source.upload_status))
                            return `<span id="status${source.id}"></span>`;
                        let html = `<span id="status${source.id}">${source.upload_status}</span>`;
                        return html;
                    }, "name": "upload_status"
                },
                {
                    "data": function (source, type, val) {
                        if (isEmpty(source.version))
                            return "";
                        let html = `<span title="${source.version}">${source.version}</span>`;
                        return html;
                    }
                },
                {
                    "data": "upload_time",
                        "render": function (value) {
                            if (value === null) return "";
                            let date = moment(value).format('YYYY-MM-DD HH:mm:ss ');
                            let html = `<span style="width:90%;word-break:normal;display:inline-block;white-space:pre-wrap;overflow:hidden title="${date}">${date}</span>`;
                            return html;
                        }, "name": "upload_time"
                },
                {
                    "data": function (source, type, val) {
                        let html = `<div style="margin-left:10px">
                                        <form id="form1" enctype="multipart/form-data" method="post" action="@Url.Action("Upload","File")?id=${source.id}">
                                            <div class ="row">
                                            <label class ="feather icon-file-plus" style="font-size: 25px; cursor:pointer" title="選擇檔案">
                                                <input type="file" name="fileToUpload" id="fileToUpload${source.id}" data-id="${source.id}" onchange="fileSelected(${source.id});" style="display:none" accept=".zip"/>
                                            </label>
                                            <a class ="feather icon-file-minus" type="button" onClick="clearFiles(${source.id});" style="font-size: 25px;cursor:pointer;" title="清除選擇檔案"></a>
                                            <a href="@Url.Action("Modify","File")?id=${source.id}" style="font-size: 25px;" class ="feather icon-edit" title="編輯"></a>
                                            <a href="@Url.Action("Delete","File")?file_id=${source.id}" onclick="return confirmAct();" style="font-size: 25px;" class ="feather icon-trash" title="刪除"></a>
                                            </div>
                                            <div id="fileName${source.id}" name="uploadFileName" class ="row" style="margin-bottom:8px;"></div>
                                            <div id="fileSize${source.id}" name="uploadFileSize" class="row"></div>
                                            <div id="fileType${source.id}"></div>
                                            <div id="progressNumber${source.id}" name="uploadProgressNum"></div>
                                        </form>
                                    </div>`;
                        return html;
                    }
                }
            ],
            ajax: {
                method: "get",
                url: "@Url.Action("SearchIndex", "File")",
            data: function (d) {
                d.category_id = $("#category_id").val();
                d.collection_id = $("#collection_id").val();
                d.academic_year_id = $("#academic_year_id").val();
            }
        },
        order: [[9, "desc"]], //預設排序資料行(由0算起)
        orderMulti: false,
        "drawCallback": function () {
            ResetTargetModalEvent();
            //ResetPreviewEvent();
        }
        });

        @*//搜尋條件-區域
        let search_district_key = "@controller" + "-" + "@action" + "-town_name";
        let search_district_val = sessionStorage.getItem(search_district_key).toString();
        $('#town_name').val(search_district_val).change();*@


        //掛上DT事件
        table.on('draw', function () {
            let info = table.page.info();
            sessionStorage.setItem(pageKey, info.page);
        });
        table.on('length', function (e, settings, len) {
            let lengthKey = "@controller" + "-" + "@action" + "-pageLength";
            sessionStorage.setItem(lengthKey, len);
        });
        //<!---datatable----------------------------------------------------------------->

        //搜索框
        $("#category_id").change(function () {
            let selected = $("#category_id option:selected");
            let val = selected.val();

            //紀錄搜尋條件
            let searchKey = "@controller" + "-" + "@action" + "-" + this.id;
            sessionStorage.setItem(searchKey, val);
            //將記錄頁碼設回0
            sessionStorage.setItem(pageKey, 0);

            //刷新table
            table.draw();
        });

        //學年度
        $("#academic_year_id").change(function () {
            let selected = $("#academic_year_id option:selected");
            let val = selected.val();
            //紀錄搜尋條件
            let searchKey = "@controller" + "-" + "@action" + "-" + this.id;
            sessionStorage.setItem(searchKey, val);


            //清空系列紀錄
            clear_search_collection();

            //change事件 觸發系列篩選
            $.ajax({
                url: "@Url.Action("Get_Collection_ByYearId", "File")",
                type: "POST",
                data: { "academic_year_id": val },
                success: function (data) {
                    $("#collection_id").empty();
                    $("#collection_id").append(`<option value="">全系列</option>`);
                    console.log(data)
                    for (let i = 0; i < data.length; i++) {
                        html = `<option value="${data[i].id}">${data[i].collection_chi}</option>`;
                        $("#collection_id").append(html);
                    }
                }
            }).done(function () { table.draw(); });
        });

        //搜索框_系列
        $("#collection_id").change(function () {
            let selected = $("#collection_id option:selected");
            let val = selected.val();

            //紀錄搜尋條件
            let searchKey = "@controller" + "-" + "@action" + "-" + this.id;
            sessionStorage.setItem(searchKey, val);
            //將記錄頁碼設回0
            sessionStorage.setItem(pageKey, 0);

            //刷新table
            table.draw();
        })


        //清空系列紀錄
        function clear_search_collection() {
            let search_collection_key = "@controller" + "-" + "@action" + "-collection_id";
            sessionStorage.setItem(search_collection_key, '');
        }


    });//load function

    // ---------------------active toggle btn-----------------------
    function active_toggle(cb, id) {
        let is_checked = cb.checked;
        $.ajax({
            url: "@Url.Action("change_active_of_file", "File")",
            type: "POST",
        data: { "is_checked": is_checked, "id": id }
    });
    }
    //is_web toggle
    function isWeb_toggle(cb, id) {
        let is_web = cb.checked;
        $.ajax({
            url: "@Url.Action("toggle_isWeb_of_file", "File")",
            type: "POST",
            data: { "is_web": is_web, "file_id": id }
        });
    }

    //is_pc toggle
    function isApp_toggle(cb, id) {
        let is_pc = cb.checked;
        $.ajax({
            url: "@Url.Action("toggle_isPc_of_file", "File")",
            type: "POST",
            data: { "is_pc": is_pc, "file_id": id }
        });
    }

    //------------------------------------大型檔案上傳------------------------------------

    window.BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;

        const BYTES_PER_CHUNK = 1048576*10; // 1MB chunk sizes.   //10mb 保險設置  原為 100

        var inLine = []; //等候上傳佇列
        var uploadOK = []; //上傳完成佇列
        var uploadFail = []; //上傳失敗項目

        var requestArr = [];
        var reqDataArr = []; //待傳項目
        var uploading = []; //正在傳的項目

        function sendRequest() {

            reqDataArr = [];
            uploading = [];
            let nextID = inLine[0];

            var blob = document.getElementById('fileToUpload' + nextID).files[0];
            let FileNo = $('#file_no' + nextID).text();
            let FileName = blob.name;
            //----------total_file_size----------
            let FileSize = blob.size;
            if (blob.size > 1024 * 1024)
                FileSize = (Math.round(blob.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
            else
                FileSize = (Math.round(blob.size * 100 / 1024) / 100).toString() + 'KB';
            //----------total_file_size----------
            //file_status
            $("#status" + nextID).html("上傳中");
            const SIZE = blob.size;
            sessionStorage.setItem("totalS" + nextID, SIZE.toString());
            const totalPart = Math.ceil(SIZE / BYTES_PER_CHUNK)
            var start = 0;
            var end = BYTES_PER_CHUNK;
            var i = 1;
            while (start < SIZE) {
                var chunk = blob.slice(start, end);
                uploadFile(chunk, i, totalPart, nextID, FileName, FileSize, FileNo);
                i++;

                start = end;
                end = start + BYTES_PER_CHUNK;
            }

            StartXHR();
            }

            function fileSelected(id) {
                // 以fileSize 來判斷之前是否已有該檔案, 若存在 則跳alert "請確認已將當前欲上傳檔案列表清空"
                let fileSizeExisted = $("#file_size" + id).text();
                let currentFile = $("#fileToUpload" + id).val();
                // console.log('fileSizeExisted', fileSizeExisted);
                // console.log('currentFile', currentFile);
                if (fileSizeExisted) {
                    $("#fileToUpload" + id).val('');
                    // console.log('currentFileClear', currentFile);
                    alert('請確認已將當前欲上傳檔案清空');
                    return;
                }

                var file = document.getElementById('fileToUpload'+id).files[0];
                if (file) {
                    var fileSize = 0;
                    if (file.size > 1024 * 1024)
                        fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
                    else
                        fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';

                    //document.getElementById('fileName'+id).innerHTML = 'Name: ' + file.name;
                    //document.getElementById('fileSize'+id).innerHTML = 'Size: ' + fileSize;
                    //document.getElementById('fileType'+id).innerHTML = 'Type: ' + file.type;
                    $("#fileName" + id).html(file.name);
                    $("#file_size" + id).html(fileSize);
                }
            }

            function uploadFile(blobFile, part, totalPart, id, FileName, FileSize, FileNo) {
                //var file = document.getElementById('fileToUpload').files[0];
                let fd = new FormData();
                fd.append("fileToUpload", blobFile);
                fd.append("part", part);
                fd.append("totalPart", totalPart);
                fd.append("id", id);
                fd.append("FileName", FileName);
                fd.append("FileSize", FileSize);
                fd.append("FileNo", FileNo)
                reqDataArr.push(fd);

                //alert("oen over");
            }

            function StartXHR() {
                reqDataArr.reverse();
                requestArr = [];//迴圈保險設置1,原本為10
                for (var i = 0; i < 1; i++) {
                    let xhr = new XMLHttpRequest();
                    //xhr.upload.addEventListener("progress", uploadProgress, false);
                    xhr.addEventListener("loadstart", loadstart, false);
                    xhr.addEventListener("load", uploadComplete, false);
                    xhr.addEventListener("error", uploadFailed, false);
                    xhr.addEventListener("abort", uploadCanceled, false);
                    xhr.addEventListener("timeout", timeout, false);
                    xhr.addEventListener("loadend", loadend, false);
                    xhr.tryTime = 0;

                    xhr.SendFD = function(){
                        let data = reqDataArr.pop();
                        uploading.push(data);
                        if(data){
                            xhr.open("POST", "@Url.Action("Upload","File")");
                            xhr.data = data;
                            xhr.tryTime++;
                            xhr.send(data);
                        }
                    }

                    requestArr.push(xhr);
                }
                //迴圈保險設置1,原本為10
                for(var i = 0; i < 1; i++){
                    requestArr[i].SendFD();
                }
            }

            function loadend(evt) {
                //console.log('loadend', this.data.get("FileName"), this.data.get("part"), this.data.get("FileNo"));

                if (inLine.length == 0) {
                    this.abort();
                    return;
                }
                let nextID = inLine[0];
                //console.log("nextID", nextID);
                //更新進度
                var current = parseInt(sessionStorage.getItem("current" + nextID));
                current += BYTES_PER_CHUNK;
                sessionStorage.setItem("current" + nextID, current.toString());

                let totalS = parseInt(sessionStorage.getItem("totalS" + nextID));

                let percentage = Math.round(current / totalS * 100);
                if (totalS < BYTES_PER_CHUNK)
                    percentage = 100;

                document.getElementById('progressNumber' + nextID).innerHTML = percentage.toString() + '%';

                //let success = CheckFileUploadSuccess(this.data.get("id"), this.data.get("part"), this.data.get("FileNo"));
                CheckFileUploadSuccess(this);

            }
            function timeout(evt) {
                //console.log('timeout', this.data.get("part"));
            }
            function loadstart(evt) {
                //console.log('loadstart', this.data.get("part"));
            }
            function uploadComplete(evt) {
                //console.log("uploadComplete", this.data.get("part"))
                //console.log("uploadComplete", inLine);

                /* This event is raised when the server send back a response */
                //alert(evt.target.responseText);
            }

            function uploadFailed(evt) {
                //console.log("uploadFailed", this.data.get("part"));
                this.abort();
                //alert("There was an error attempting to upload the file.");

            }

            function uploadCanceled(evt) {
                //console.log("uploadCanceled", this.data.get("part"));
                //xhr.abort();
                //xhr = null;
                //alert("The upload has been canceled by the user or the browser dropped the connection.");
            }

            function CheckFileUploadSuccess(df_obj) {
                let upload_success = false;
                $.ajax({
                    url: "@Url.Action("CheckFileExist", "File")",
                    type: "POST",
                    data: { "id": df_obj.data.get("id"), "part": df_obj.data.get("part"), "FileNo": df_obj.data.get("FileNo") },
                    async: true,
                    success: function (data) {
                        upload_success = data;
                    }
                }).done(function () {
                    console.log(df_obj.data.get("part") + " upload " + upload_success);
                    if (upload_success) {
                        console.log('3');
                        let deleteIndex = uploading.indexOf(p=>p.get("part") === df_obj.data.get("part"));
                        if (deleteIndex > -1)
                            uploading.splice(deleteIndex, 1);

                        if (reqDataArr.length > 0){
                            df_obj.tryTime = 0;
                            df_obj.SendFD();
                        }
                        else {
                            console.log('4');
                            let index = requestArr.indexOf(df_obj);
                            console.log('index',index);
                            if (index > -1) {
                                requestArr.splice(index, 1);
                            } else {
                                console('continue')
                            }

                            let nextID = inLine[0];
                            let totalS = parseInt(sessionStorage.getItem("totalS" + nextID));
                            let is_small_file = (totalS < BYTES_PER_CHUNK);
                            console.log('is_small_file',is_small_file);
                            if (requestArr.length === 0||(is_small_file)) {
                                $("#status" + nextID).html("解析中");
                                $("#progressNumber" + nextID).html('100%')
                                let needUnCompress = CheckUnCompress(df_obj.data.get("id"));
                                if (needUnCompress) {
                                    console.log('要解壓縮')
                                    $("#status" + nextID).html("解壓縮中");
                                }

                                uploadOK.push(nextID);
                                inLine.splice(0, 1);

                                console.log("剩餘佇列", inLine)
                                if (inLine.length > 0) {
                                    sendRequest();//繼續上傳下一個
                                    console.log('繼續傳下一個')
                                }
                                else {
                                    console.log("全部上傳完畢-->解壓縮", uploadOK);
                                    //dosomthing
                                    merge_unzip();
                                }

                            }
                        }
                    }
                    else {
                        console.log("File Not Found", df_obj.data.get("part"));
                        if (df_obj.tryTime < 3) {
                            current -= BYTES_PER_CHUNK;
                            df_obj.open("POST", "@Url.Action("Upload","File")");
                            df_obj.send(df_obj.data);
                        }
                        else {
                            df_obj.SendFD();
                        }

                    }


                })
            }

            function CheckUnCompress(file_id) {
                let result = false;
                $.ajax({
                    url: "@Url.Action("CheckUnCompress", "File")",
                    type: "POST",
                    data: { "id": file_id },
                    async: false,
                    success: function (data) {
                        result = data;
                    }
                });

                return result;
            }

            function clearFiles(file_id) {
                if (!confirm("您確定要清空?")) {
                    return false;
                }
                //清空選擇檔案
                let upload_obj = document.getElementById('fileToUpload' + file_id);
                upload_obj.outerHTML = upload_obj.outerHTML;

                $("#status" + file_id).html("清空");
                $("#file_size" + file_id).html("");
                $("#fileName" + file_id).html("");
                $("#progressNumber" + file_id).html("");
                $.ajax({
                    url:"@Url.Action("ClearFile","File")",
                    type: "POST",
                    data: { "file_id": file_id },
                    success: function () {
                        toastr.success("檔案清空完畢", 'Success:');
                    }

                })
            }
            //佇列上傳
            function run_upload_list() {

                inLine = [];
                var files = $("input[type='file']");
                files.each(function (index) {
                    let file_onload = $(this).val();
                    let data_id=$(this).attr('data-id');
                    if(!isEmpty(file_onload)){
                        console.log('start upload' + index + ' : ' + data_id);
                        inLine.push(data_id)
                    }
                })

                //警告字
                if (inLine.length > 0) {
                    $("#alert_phrase").text('請勿操作 以免傳輸檔案遺失');
                    $("#alert_phrase").css('color', 'red');
                } else {
                    alert('沒有任何掛載檔案');
                    return;
                }
                console.log(inLine);
                //陣列這物件如果有 就執行上傳
                //first one

                for (var i = 0; i < inLine.length; i++) {
                    sessionStorage.setItem("current" + inLine[i], "0");
                    sessionStorage.setItem("totalS" + inLine[i], "0");
                }
                requestArr = [];
                reqDataArr = [];
                sendRequest();
            }

            function merge_unzip() {
                let new_merge_id = uploadOK[0];
                let file_id = new_merge_id;
                console.log('a')
                let fileNo = $("#file_no" + file_id).text();
                console.log('b')
                let needUnZip = ($("#status" + file_id).text() === '解壓縮中');
                console.log(" file_id :", file_id, " fileNo :", fileNo, " needUnZip :", needUnZip)
                $.ajax({
                    url: "@Url.Action("Merge_Unzip", "File")",
                    type:"POST",
                    data: { "file_id": file_id, "fileNo": fileNo,"needUnZip":needUnZip },
                    success: function (data) {
                        console.log('unzip', data);
                        uploadOK = uploadOK.slice(1);
                        console.log(uploadOK)
                        if (data == 201) {
                            $("#status" + new_merge_id).html("上傳成功");
                        }
                        if (data == 200) {
                            $('#status' + new_merge_id).html("解壓縮成功")
                        }
                        if (uploadOK.length > 0) {
                            merge_unzip();
                        }
                        //全部檔案上傳完畢
                        if (uploadOK.length == 0) {
                            toastr.success("操作成功", 'Success:');
                            clearAllFiles();
                            $("#alert_phrase").text('上傳成功!')
                            $("#alert_phrase").css('color', '#0ac282');
                        }

                    }
                })
            }

    //清空選擇上傳檔案
    function clearAllFiles() {
        $("input[name=fileToUpload]").val('');
        $("div[name=uploadFileName]").empty();
        $("div[name=uploadFileSize]").empty();
        $("div[name=uploadProgressNum]").empty();
    }


    //------------------------------------大型檔案上傳------------------------------------

    //刪除array 中指定的value
    Array.prototype.removeByValue =
        function (val) {
            for (var i = 0; i < this.length; i) {
                if (this[i] == val) {
                    this.splice(i, 1);
                    break;
                }
            }
        }

    //確認要刪除嗎
    function confirmAct() {
        if (confirm('確定要刪除嗎?')) {
            return true;
        }
        return false;
    }
</script>

web.config need to pay attention to these two parts.

  <system.web>
    <httpRuntime targetFramework="4.5.2" maxRequestLength="2147483647" executionTimeout="1600" maxQueryStringLength="10240"  requestLengthDiskThreshold="102400"/>
  <system.web>

   <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2147483647" maxQueryString="32768" />
      </requestFiltering>
    </security>
   <system.webServer>
#largefile #upload #C# #javascript #razor






Related Posts

每日心得筆記 2020-06-27(六)

每日心得筆記 2020-06-27(六)

關於 物件 Object - 取值、新增、刪除

關於 物件 Object - 取值、新增、刪除

【PHP】畫面一片空白、直接噴 500?兩行程式讓後端乖乖報錯

【PHP】畫面一片空白、直接噴 500?兩行程式讓後端乖乖報錯






Comments