Recently were working on uploading a zip file to S3 using presigned url. We exposed an API to client for generating a presigned url over an authenticated API call. After generating presigned URL client is supposed to send content in a PUT call to S3 on the presigned url. But when we tried sending the file using MultipartRequest the file got corrupted. After struggling for a long time we found StreamedRequest using which we were able to upload the file to S3 without getting it corrupted. Following is the code for uploading the file to S3.
Future<http.StreamedResponse?> uploadFileToS3(
String s3Url,
file_picker.PlatformFile file,
) async {
var request = http.StreamedRequest('PUT', Uri.parse(s3Url));
final streamSink = request.sink as StreamSink<List<int>>;
print('Uploading file '+file.name+' to '+s3Url);
var resp = request.send();
await streamSink.addStream(file.readStream!);
streamSink.close();
print('returning response for '+file.name);
return await resp;
}
Please note readStream will be null if you don't pass required arguments to file_picker. The required arguments for file picker are:
FilePickerResult? result = await FilePicker.platform.pickFiles(withData:false, withReadStream: true);
Please let me know if you face any problem in using this approach.
No comments:
Post a Comment