天天看點

jQuery檔案分片上傳

前端代碼:
<input type="file" id="file6" multiple>
<button type="button" class="btnFile6">分片上傳6</button>
<div class="result"></div>
//方式6
 $(".btnFile6").click(function () { 
     var upload = function (file, skip) {
         var formData = new FormData();//初始化一個FormData對象
         var blockSize = 1000000;//每塊的大小
         var nextSize = Math.min((skip + 1) * blockSize, file.size);//讀取到結束位置             
         var fileData = file.slice(skip * blockSize, nextSize);//截取 部分檔案 塊
         formData.append("file", fileData);//将 部分檔案 塞入FormData
         formData.append("fileName", file.name);//儲存檔案名字
         $.ajax({
             url: "/Home/SaveFile6",
             type: "POST",
             data: formData,
             processData: false,  // 告訴jQuery不要去處理發送的資料
             contentType: false,   // 告訴jQuery不要去設定Content-Type請求頭
             success: function (responseText) {
                 $(".result").html("已經上傳了" + (skip + 1) + "塊檔案");
                 if (file.size <= nextSize) {//如果上傳完成,則跳出繼續上傳
                     alert("上傳完成");
                     return;
                 }
                 upload(file, ++skip);//遞歸調用
             }
         });
     };

     var file = $("#file6")[0].files[0];
     upload(file, 0);
 }); 
           

  

背景代碼:
public string SaveFile6()
{
    //儲存檔案到根目錄 App_Data + 擷取檔案名稱和格式
    var filePath = Server.MapPath("~/App_Data/") + Request.Form["fileName"];
    //建立一個追加(FileMode.Append)方式的檔案流
    using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write))
    {
        using (BinaryWriter bw = new BinaryWriter(fs))
        {
            //讀取檔案流
            BinaryReader br = new BinaryReader(Request.Files[0].InputStream);
            //将檔案留轉成位元組數組
            byte[] bytes = br.ReadBytes((int)Request.Files[0].InputStream.Length);
            //将位元組數組追加到檔案
            bw.Write(bytes);
        }
    }
    return "儲存成功";
}
           

  

轉載于:https://www.cnblogs.com/fjzhang/p/7227401.html

繼續閱讀