Flutter: upload Image error via API function

424 views Asked by At

I'm trying to upload images and some data via API from my app and I have no error in my console and I don't know what's wrong with my function. This is the code which I use:

upload(File imageFile) async {
    var user =
        Provider.of<LoginUserProvider>(context, listen: false).userData.data;
    DateFormat formater = DateFormat('yyyy-MM-dd');
    String formatted = formater.format(dateTime);
    var stream =
        // ignore: deprecated_member_use
        new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
    var length = await imageFile.length();

    var headers =
        Provider.of<LoginUserProvider>(context, listen: false).httpHeader;

    var uri = Uri.parse(
        "xyz");

    var request = new http.MultipartRequest("POST", uri);
    request.headers.addAll(headers);
    //request.headers.addAll(Environment.requestHeaderMedia);
    var multipartFile = new http.MultipartFile(
      'attachment',
      stream,
      length,
      filename: imageFile.path,
      contentType: MediaType('application', 'x-tar'),
    );
    request.fields['section_id'] = VillaID.toString();
    request.fields['date'] = formatted;
    request.fields['description'] = descriptionController.text;

    request.files.add(multipartFile);
    var response = await request.send();
    print(response.statusCode);
    response.stream.transform(utf8.decoder).listen((value) {
      print(value);
    });

    try {
      final streamedResponse = await request.send();
      final response = await http.Response.fromStream(streamedResponse);
      print(json.decode(response.body));
      final responseData = json.decode(response.body) as Map<String, dynamic>;

      if (response.statusCode == 200 || response.statusCode == 201) {
        return true;
      }catch (error) {
      print(error);
      return false;
    }
    return true;
  }

So can anyone help me with my issue, please!

1

There are 1 answers

2
MRazaImtiaz On

you are sending the same request twice

1st

var response = await request.send();

Second

final streamedResponse = await request.send();

before sending the same request, create them again.

regarding your code you don't need to create a response again. use the first one in the other places.