Angular 示例
tsx
import { Component } from '@angular/core';
import { createUploader, Config, UploadOptions } from 'enlarge-file-upload';
import axios from 'axios';
@Component({
selector: 'app-uploader',
templateUrl: './uploader.component.html',
styleUrls: ['./uploader.component.css']
})
export class UploaderComponent {
progress = 0;
speed = '0 MB/s';
uploader = createUploader(this.getUploaderConfig());
// 上传函数
async uploadFunction({ chunk, index, hash, cancelToken }: UploadOptions): Promise<void> {
const formData = new FormData();
formData.append('chunk', chunk);
formData.append('index', index.toString());
formData.append('hash', hash);
await axios.post('http://xxxx/api/upload', formData, {
cancelToken
});
}
// 获取上传配置
getUploaderConfig(): Config {
return {
chunkSize: 0.01 * 1024 * 1024, // 约等于 10KB 示例
concurrency: 5,
maxRetries: 3,
uploadFunction: this.uploadFunction.bind(this),
onProgress: (progressValue: number) => {
this.progress = progressValue;
},
onSuccess: () => {
console.log('上传完毕');
},
onSpeed: (speedValue: string) => {
this.speed = speedValue;
}
};
}
onFileSelected(event: Event) {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (file) {
this.uploader.upload(file);
}
}
pauseUpload() {
this.uploader.pause();
}
resumeUpload() {
this.uploader.resume();
}
}