如何在 angular 中以块的形式上传视频文件(版本 8)

How to upload video files as chunks in angular (version 8)

我想使用 angular HttpClient in angular 和 aspnetcore web API 将大型视频文件作为块上传到服务器,因为我在使用 multipart 时遇到文件大小限制问题文件上传。

angular 中分块视频文件的一种可能方法:

HTML 视图包含一个文件类型的输入,它在文件上传时触发 component.ts 上的一个函数。该组件的功能应验证文件类型是否为视频,然后将其分成小块。可以使用外部服务来管理每个块并将其发送到 API。然后后端应该负责接收每个块并将其合并为最终文件。

这是一个简单的示例,说明了从 UI 到 API 的编程过程。这些脚本非常基础,但它们显示了流程。您应该实施文件验证、try/caching 和其他改进以确保其安全。

component.html

<input type="file" (change)="fileSelected($event)" />

component.ts

async fileSelected(file) {
    const chunkSize = 40000;

    for( let offset = 0; offset < file.size; offset += chunkSize ){
        const chunk = file.slice( offset, offset + chunkSize );
        const apiResponse = await this.apiService.sendChunk( chunk, offset );
    }
}

service.ts

sendChunk( chunk, offset ) {
   const APIurl = 'http://myapi.com';
   const data = {
       chunk: chunk,
       offset: offset
   };
   return this.http.post(APIurl, data);
}

本机 javascript 的几个参考以及其他实现: and link2

启迪图书馆

另一种可能的解决方案是使用 tus 库,它会为您分块上传,并允许按需暂停和恢复上传 - 即使客户端或服务器连接崩溃,上传仍然可以在以下时间恢复连接恢复。

不幸的是,该库必须在服务器端和客户端实现,这使得支持所有 server/client 类型变得很麻烦。有可用的社区 dotNet 库 here. For implementation in Angular, you can use the official tus-js-client library. The tus team also provide a live demo for you to test: demo


Angular 客户端示例

An example Angular client for file uploads to tus server:

(The upload server used in this example is https://master.tus.io/files/)

https://stackblitz.com/edit/angular-tus-client

Please note that a lot of the code implemented in my example is available on the tus-js-client library. Here is another resource I used for understanding tus angular implementation. I am also not affiliated with the library or the creators of the library. I just stumbled upon it in my search for robust upload technology.