分割檔案上傳V2 ( 像續傳一樣傳多少收多少 )

  • 1262
  • 0

上一個版本因為假如檔案過大,而切割的又過小的話容易造成同一個資料夾中多個檔案產生,雖不影響最後結果,但看著也不太酥胡
後來稍微改良一下,以檔案附加的方式一片一片的加上去,程式碼的部份還是以實際開發該進行驗證的還是要驗證,我是使用前端傳個時間刻印進行驗證,
讓多人使用的時後不會造成同個檔案被覆蓋的問題。

在Controller因非同步處理速度過快會導致在判斷刪檔時易出現錯誤,目前解決方式是透過try catch包住,雖無法解決根本問題,但整體使用上是可行的,
以後如果有更好的方式再做調整吧。

Javascript

<script>
        $(function () {
            page.init();
        });

        var page = {
            init: function () {
                $("#upload").click($.proxy(this.upload, this));
            },
            upload: function () {

                var file = $("#file")[0].files[0],
                    name = file.name,
                    size = file.size,
                    stamp = Date.now(),
                    succeed = 0;

                var ext
                var extIndex = name.lastIndexOf('.');
                if (extIndex != -1) {
                    ext = name.substr(extIndex + 1, name.length);
                }

                var shardSize = 2 * 1024 * 1024,    //以2MB为主
                    shardCount = Math.ceil(size / shardSize);  //總切片數

                var deferreds = [];
                var res = [];
                for (var i = 0; i < shardCount; ++i) {

                    //計算起始與結束位置
                    var start = i * shardSize,
                        end = Math.min(size, start + shardSize);

                    //FormData
                    var form = new FormData();
                    form.append("data", file.slice(start, end));  //slice方法用于切出文件的一部分
                    form.append("name", name);
                    form.append("stamp", stamp);
                    form.append("ext", ext);
                    form.append("size", size);
                    form.append("total", shardCount);  //總數
                    var indexx = i + 1;
                    form.append("index", indexx);        //目前是第幾個檔

                    //Ajax提交
                    deferreds.push(
                        $.ajax({
                            url: "@Url.Action("Upload2", "FileHandle")",
                            type: "POST",
                            data: form,
                            async: true,        //是否採非同步進行
                            processData: false,
                            contentType: false,
                            success: function (data) {
                                ++succeed;
                                $("#output").text(succeed + " / " + shardCount);
                            }
                        })
                    );
                }

                $.when.apply($, deferreds).done(function () {

                     //待切割檔案上傳全處理完成後,處理後續相關動作
                     //我自己的處理方式是將input file設為零,只做form data的處理

                });
            }
        };
    </script>

Html

<input type="file" id="file" />
<button id="upload">上傳</button>
<span id="output" style="font-size:12px">等待</span>

C# Controller

        public ActionResult Upload2()
        {

            string savename = Request["name"];
            string stamp = Request["stamp"];
            string ext = Request["ext"];

            int total = Convert.ToInt32(Request["total"]);
            int size = Convert.ToInt32(Request["size"]);
            int index = Convert.ToInt32(Request["index"]);
            var data = Request.Files["data"];

            string dir = "D:/slicefile";
            string file = Path.Combine(dir, stamp);
            string file2 = Path.Combine(dir, savename);
            try
            {
                var fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);

                byte[] fileData = null;
                using (var binaryReader = new BinaryReader(data.InputStream))
                {
                    fileData = binaryReader.ReadBytes(data.ContentLength);
                }

                //依目前是第幾個切片數移至該點進行寫入類似多點寫入,少這一段會造成檔案錯亂
                //檔案大小需和前端所判斷的大小相同,可寫在webconfig setting中在一併透過同個設定處理
                fs.Seek((index - 1) * (2 * 1024 * 1024), SeekOrigin.Begin);
                fs.Write(fileData, 0, fileData.Length);
                fileData = null;

                var filelength = fs.Length;
                fs.Close();
                if (filelength == size)
                {
                    return Json(new { success = true, message = "切割上傳成功" }, "text/html");//成功
                }

            }
            catch (Exception)
            {
                return Json(new { success = false, message = "檔案處理中" }, "text/html");//成功
            }

            return Json(new { success = false, message = "切割上傳進行中" }, "text/html");//成功

        }