我正在尝试创建一个服务,将一个大文件分成块并将其发送到重新组装它的php页面。
@Injectable()
export class FileSplitterService {
private serviceName: String = "FileSplitterService";
public file: File;
public fileSize: number;
private chunkSize: number = 64*1024;
private offset: number = 0;
constructor(private _http: Http) {
console.log(this.serviceName + ' - constructor');
}
startSplit(event) {
console.log(this.serviceName + ' - startSplit');
/**
* Initialize offset and file stuffs
*/
this.file = event.files[0];
this.fileSize = this.file.size;
this.offset = 0;
console.log(this.serviceName + ' - startSplit',this.file,this.fileSize,this.offset);
/**
* Start reading file
*/
this.chunkReaderBlock();
}
readEventHandler(evt) {
console.log(this.serviceName + ' - readEventHandler',evt);
if (evt.target.error == null) {
this.offset += evt.target.result.length;
/**
* send chunk
*
*/
this._http.post("https://10.134.77.77/web2/api/uploadFile.php",evt.target.result)
.map(res => <any>res )
.subscribe(res=>{
if (this.offset >= this.fileSize) {
console.log(this.serviceName + ' - Done reading file');
} else{
// read next chunk
console.log(this.serviceName + ' - readEventHandler -> read next chunk', this.offset);
this.chunkReaderBlock();
}
});
} else {
console.log(this.serviceName + ' - Read error: ' + evt.target.error);
return;
}
}
chunkReaderBlock() {
console.log(this.serviceName + ' - chunkReaderBlock', this.offset, this.chunkSize, this.file);
var r: FileReader = new FileReader();
var blob = this.file.slice(this.offset, this.chunkSize + this.offset);
r.onload = (e) => {
console.log(this.serviceName + ' - onload',e);
this.readEventHandler(e)
};
r.readAsText(blob);
}
}
我的第一个版本的服务适用于大文本文件,但是当我尝试使用FileReader的 readAsArrayBuffer 方法(而不是readAsText)来分割二进制文件(如视频)时会出现问题。看来,在第一次阅读之后,onLoad函数返回一个空的事件对象。 有人能帮我吗?感谢。