Coder Social home page Coder Social logo

chunk-upload-demo's Introduction

基於 Node(express) 的文件切片上傳 demo

項目啟動

啟動命令後,訪問localhost:3000

  npm install // 安裝依賴
  node server.js

說明

  • 前端指定 chunkSize 切片大小, 利用 Blob.slice() 切片, 注意上傳切片的idx要一並帶上 (這裡是包含在上傳文件名中blobName中的index)。切片的idx關係到後端合併切片的順序。

      let blob = file.slice(start, start + chunkSize);
      let blobName = `${fname}.${index}.${fext}`;
      let blobFile = new File([blob], blobName)
  • express 根據文件名及idx 創建暫時目錄存放切片,以idx的形式命名。如收到一個文件名為 haha.1.mp4 的切片,則創建一個暫時目錄 haha,內部文件名則是 1,2,3 這種純數字的形式。

    • haha
      • 1
      • 2
      • 3
      • ...
  • 前端上傳完最後一個切片,掉用 /merge api 通知 express 合併所有切片

  • express 用 stream + promise的形式合併。寫入流需要指定寫入的位置(start),這樣可以支持並發執行寫入,而不需要串行執行。

      const start = idx * chunkSize;
      // 指定位置寫入數據
      const writeStream = fse.createWriteStream(targetFile, {
        start,
      });
  • 最後注意Promise.all中,需監聽讀取流,寫入流的錯誤事件。異常時reject promise。

      readStream.on('error', reject);
      writeStream.on('error', reject);
  • 支持指定合並文件時的最大並發數(concurrencyLimit變量)。限制並發操作的數量,可以有效地控制資源的使用情況。如果沒有並發限制,在處理大量文件時,可能會同時打開過多的文件句柄,消耗大量的內存和系統資源。通過設置最大並發數量,可以確保資源在合理範圍內使用,避免過度占用系統資源。

chunk-upload-demo's People

Contributors

malarkey-jhu avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.