I'm trying to create a service that splits a big file in chunks and send it to a php page that reassemble it.
@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);
}
}
This first version of my service works well with big text files, but the problems comes when I try to split binary files (like videos) using readAsArrayBuffer method of FileReader (instead of readAsText). It seems that after first reading, the onLoad function returns an empty event object. Can someone help me? Thanks.