Search code examples
c#asp.netflutterdartmultipart

How can I solve FileSystemException: Cannot retrieve length of file, path ='...' (OS Error: No such file or directory, errno = 2)


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']="jake-username2@gmail.com";
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


Solution

  • 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 Files in the project folders.