Ced Ced - 4 months ago 10
Dart Question

Dart file upload: Larger files aren't uploaded completely

I implemented a fileupload with dart.
This is what my client does:

Future upload(String url, File file){
Completer completer = new Completer();
FileReader fileReader = new FileReader();
fileReader.onLoad.listen((e){
HttpRequest request = new HttpRequest();
Map<String,String> headers = createHeaders();
request.open('POST',url);
for(String key in headers.keys){
request.setRequestHeader(key,headers[key]);
}
request.send(fileReader.result);
});
fileReader.onLoadEnd.listen((e)=>completer.complete());
fileReader.readAsArrayBuffer(file);
return completer.future;
}


And this is what the server does:

Future saveFileContent(String fileId, HttpRequest request)async{
Completer completer = new Completer();
File file = new File('${pathResolver.files}/${fileId}');
await file.create(recursive: true);
request.listen((data){
file.writeAsBytesSync(data);
},onDone: (){
completer.complete();
});
return completer.future;
}


For small files everything works fine, but when i try to upload a larger file,about 20MB in my testcase, just some MB are saved on the server. Has some one a idea where all those bytes got lost?

Answer

writeAsByteSync will truncate any existing file so indeed the last data receveived will be written and previously received data will be erased. You can try to create the file first and then use the parameter mode: FileMode.APPEND for writeAsByteSync