分享一個 asp.net core 多檔案分塊同時上傳的元件

IWing發表於2023-12-11

分享一個可多個檔案同時上傳、斷點續傳,並實時反饋上傳進度的 Asp.Net core 元件。

伺服器端


引用 nuget 包:JMS.FileUploader.AspNetCore

然後啟用上傳元件:

            app.UseAuthorization();
            app.MapControllers();

             //啟用上傳元件,並限制單個檔案最大100M
            app.UseJmsFileUploader(1024*102400);
            
            app.Run();

在 Controller 裡面,寫個 Test 函式,處理上傳的檔案:

    [ApiController]
    [Route("[controller]/[action]")]
    public class MainController : ControllerBase
    {

        [HttpPost]
        public string Test([FromBody] object body)
        {
            var customHeader = Request.Headers["Custom-Header"];
            
            //臨時檔案路徑
            var filepaths = Request.Headers["FilePath"];

            //檔名
            var filenames = Request.Headers["Name"];
            return filenames;
        }
    }

檔案上傳完畢,儲存在臨時檔案中,Request.Headers["FilePath"] 可以讀取這些檔案的路徑,如果確定要保留這些檔案,用 File.Move 把它們移到你的目標資料夾當中;

Request.Headers["Name"] 則是讀取檔名。

前端

引入 jms-uploader 元件:

      import JmsUploader from "jms-uploader"

html 元素:

    <input id="file1" multiple type="file" />
    <input id="file2" multiple type="file" />
    <button onclick="upload()">
        upload
    </button>
    <div id="info"></div>

javascript 指令碼:

    async function upload() {
        //自定義請求頭
        var headers = function () {
            return { "Custom-Header": "test" };
        };

        //提交的body
        var dataBody = {
            name: "abc"
        };

        var uploader = new JmsUploader("http://localhost:5200/main/test", [document.querySelector("#file1").files, document.querySelector("#file2").files], headers, dataBody);

        uploader.setPartSize(1024);//設定分塊大小,預設是102400

        uploader.onUploading = function (percent, uploadedSize, totalSize) {
            document.querySelector("#info").innerHTML = percent + "% " + uploadedSize + "," + totalSize;
        };

        var ret = await uploader.upload();
        //上傳完畢
        alert(ret);
    }


元件原始碼地址

https://github.com/simpleway2016/JMS.FileUploader.git

相關文章