I am trying to send a user model from dart to the api where my file is set as "IFormFile" data type in my c# backend. I tried using the multipart request but all i get is the error stated , i can't understand why it cannot retrieve the length of file.
This is my code:
updateUser() async {
var uri = Uri.parse('http://myIP:8070/api/Users');
var request = http.MultipartRequest('Put', uri);
request.fields['id']="07bb2a17-7cd5-471b-973a-4b77d239b6c3";
request.fields['username']="beeso";
request.fields['email']="[email protected]";
request.fields['password']="Jake123-";
request.fields["oldPassword"]="Jake124-";
request.fields["gender"]="Male";
request.fields["dateOfBirth"]=DateTime.now().toString();
request.fields["name"]="dsjnss";
request.fields["languages"]=["Language1","Language2"].toString();
request.fields["nationalities"]=["Nationality1","Nationality2"].toString();
request.fields["phoneNumber"]="70502030";
request.fields["biography"]="jdnknkdas";
request.fields["info"]="asndasnkdas";
request.fields["religion"]="Christian";
request.fields["location"]="LA";
File imageFile = new File('Anatomy_of_a_Sunset-2.jpg');
var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var multipartFile = new http.MultipartFile('file', stream, length,
filename: basename(imageFile.path));
request.files.add(multipartFile);
Map<String, String> headers = {
"content-type": "application/json"
};
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
print(response.statusCode);
}
Any help would be appreciated.
This picture shows where my file is located
In Flutter, you can't access files directly from the project. You need to add them to an assets folder (typically assets
) and also to pubspec.yaml
. Then, instead of using File
to read them, you use rootBundle
(or one of the Asset
classes).
var multipartFile = http.MultipartFile.fromBytes(
'file',
(await rootBundle.load('assets/anatomy.jpg')).buffer.asUint8List(),
filename: 'anatomy.jpg', // use the real name if available, or omit
contentType: MediaType('image', 'jpg'),
);
request.files.add(multipartFile);
While testing your API, you may find it easier to just create a Dart command line project, where you do have access to File
s in the project folders.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With