File upload using flutter and api/resource/file

Hi i am trying to upload an image using flutter http multipart file upload, but i keep getting the error
exception: AttributeError: 'bytes' object has no attribute 'update', Can anyone please help?

Future<void> uploadPhoto(photoPath) async {
  var url = Uri.https(apiUrl, '/api/resource/File');

  Map<String, String> reqHeaders = {
    HttpHeaders.contentTypeHeader: 'multipart/form-data',
    HttpHeaders.authorizationHeader:
        'Basic ${base64.encode(utf8.encode('$apiKey:$apiSecret'))}',
    HttpHeaders.acceptHeader: 'application/json, text/plain',
  };

  // final response = await http.post(
  //   url,
  //   headers: requestHeaders,
  //   body: jsonEncode({'doctype': 'Incident'}),
  // );

  // multipart upload
  var request = http.MultipartRequest('POST', url);
  Map<String, String> requestBody = <String, String>{
    'doctype': 'Incident',
    'fieldname': 'photo',
    'docname': 'test'
  };
  request.headers.addAll(reqHeaders);
  request.fields.addAll(requestBody);
  request.files.add(http.MultipartFile.fromBytes(
    'image',
    File(photoPath).readAsBytesSync(),
    filename: 'test.jpg',
  ));
  var response = await request.send();
  final respStr = await response.stream.bytesToString();

  print(request.files);
  print(
    jsonDecode(respStr),
  );

  if (response.statusCode == 200) {
    // return jsonDecode(response.body)['data'];
  } else {
    throw Exception('Failed to upload Photo');
  }
}

i found the solution, i was using the wrong endpoint

Future<void> uploadPhoto(photoPath) async {
  var url = Uri.https(apiUrl, '/api/method/upload_file');

  Map<String, String> reqHeaders = {
    HttpHeaders.contentTypeHeader: 'multipart/form-data',
    HttpHeaders.authorizationHeader:
        'Basic ${base64.encode(utf8.encode('$apiKey:$apiSecret'))}',
    HttpHeaders.acceptHeader: 'application/json',
  };

  // multipart upload
  var request = http.MultipartRequest('POST', url);
  Map<String, String> requestBody = <String, String>{
    'doctype': 'Incident',
    'fieldname': 'photo',
    'docname': 'test'
  };
  request.headers.addAll(reqHeaders);
  request.fields.addAll(requestBody);
  request.files.add(http.MultipartFile.fromBytes(
    'file',
    File(photoPath).readAsBytesSync(),
    filename: 'test.jpg',
  ));
  var response = await request.send();
  final respStr = await response.stream.bytesToString();

  print(
    jsonDecode(respStr),
  );

  if (response.statusCode == 200) {
    // return jsonDecode(response.body)['data'];
  } else {
    throw Exception('Failed to upload Photo');
  }
}
2 Likes