skip to Main Content

I am trying to post files (html files since working on web) to the API.
I am getting an error saying Null is not a subtype of type InstanceRef in type cast.
I don’t know what is causing this. Everything seems to be fine to me in the code.

Here is the code:

          uploadFiles() async {
            ///
            try {
              var token =
                  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiIyIiwibmJmIjoxNjc5MzgzMTY5LCJleHAiOjE2NzkzODQ5NjksImlhdCI6MTY3OTM4MzE2OX0.HL5Y39p0cxpbuOhbls-hjq2Nu_xnVGAJ4qacESp1yNw';
              var url =
                  Uri.parse("my_url");
              var request = http.MultipartRequest('POST', url);
              Map<String, String> headers = {
                "Authorization": "Bearer $token",
                "Content-type": "multipart/form-data"
              };
              request.headers.addAll(headers);

              request.fields
                  .addAll({"facility_id": "46", "module_id": "3263", "id": "1"});

              for (var file in files) {
                var reader = html.FileReader();
                reader.readAsArrayBuffer(file);

                var completer = Completer<List<int>>();
                bool _isCompleted = false; // add this flag

                reader.onLoadEnd.listen((event) {
                  if (!_isCompleted) {
                    // check if already completed
                    _isCompleted = true;
                    completer.complete(reader.result as List<int>);
                  }
                });
                var filename = file.name;
                var multipartFile = http.MultipartFile.fromBytes(
                  'file',
                  (await completer.future),
                  filename: filename,
                );
                request.files.add(multipartFile);
              }

              var response = await request.send();

              if (response.statusCode == 200) {
                print('Upload successful');
              } else {
                print('Upload failed');
              }
            } //
            catch (e) {
              print(e);
            }
          }

4

Answers


  1. Chosen as BEST ANSWER

    This is what finally worked for me:

              ///
          Future<void> upload() async {
            for (var i = 0; i < files.length; i++) {
              final file = files[i];
              final completer = Completer<List<int>>();
              final reader = FileReader();
    
              reader.onLoad.listen((event) {
                final bytesData = reader.result as List<int>;
                completer.complete(bytesData);
              });
    
              reader.readAsArrayBuffer(file);
              final bytesData = await completer.future;
              final request = http.MultipartRequest("POST", Uri.parse(url));
              final headers = {
                "Authorization": "Bearer $token",
                "Content-Type": "multipart/form-data",
                "Content-Length": bytesData.length.toString(),
                "Accept": "*/*",
              };
              request.headers.addAll(headers);
              if (requestFields != null) {
                request.fields.addAll(requestFields!);
              }
              request.files.add(http.MultipartFile.fromBytes(
                'files',
                bytesData,
                filename: file.name,
              ));
              final response = await request.send();
              handleResponse(response);
            }
          }
    

    Turns out content-length was required.


  2. for file upload you should send with "Content-type": "multipart/form-data"

    Future<int> uploadFile({File file,String filename,String token})async{
        ///MultiPart request
        var request = http.MultipartRequest(
            'POST', Uri.parse("https://your api url with endpoint"),
    
        );
        Map<String,String> headers={
          "Authorization":"Bearer $token",
          "Content-type": "multipart/form-data"
        };
        request.files.add(
            http.MultipartFile(
               'file',
                file.readAsBytes().asStream(),
                file.lengthSync(),
                filename: filename,
              contentType: MediaType('image','jpeg'),
            ),
        );
        request.headers.addAll(headers);
    
        /// optional if require to add other fields then image
    
        request.fields.addAll({
          "name":"test",
          "email":"[email protected]",
          "id":"12345"
        });
        print("request: "+request.toString());
        var res = await request.send();
        print("This is response:"+res.toString());
        return res.statusCode;
      }
    }
    
    Login or Signup to reply.
  3. there are two possible way

    1 – Multipart
    2 – Base64Decode

    static Future Uploadingusingmultipart({
        var courseid,
        var feedback,
        var filename,
      }) async {
        try {
          
          var request = http.MultipartRequest(
              'POST',
              Uri.parse(
                  '${BaseUrl.baseurl}/apilink'));
          request.headers["authorization"] =  BaseUrl.storage.read("logintoken");
    
          request.fields['courseid'] =
              "${courseid}";
          request.fields['Feedback'] = "${feedback}";
          if (filename != '') {
            request.files.add(new http.MultipartFile.fromBytes(
                'Image', File(filename).readAsBytesSync(),
                filename: filename.split("/").last));
          }
          var res = await request.send();
          final response = await http.Response.fromStream(res);
    
          print(response.body);
          return response;
        } catch (e) {
          print(e);
          // return onError(e, "login/Users/login");
        }
      }
    

    In this you upload file using fileupload!.files.single.path,

    Uploadingusingmultipart(
            courseid: fieldid,
            feedback: '',
            filename: fileupload!.files.single.path,
          )
    

    The Other way is using Base64

     final bytes = File(pickedFile!.files.single.path).readAsBytesSync();
     String base64Image ="data:image/png;base64," +base64Encode(bytes);
    

    In this you call api normally

    Login or Signup to reply.
  4. Very Simple solutions
    Add and import library

     import 'package:path/path.dart' as path;
    import 'package:async/async.dart';
    convert XFile? imageURI; to file
    Submit(File(imageURI!.path));
     
    Submit(filepath) async { 
        var request = new http.MultipartRequest(
            "POST", Uri.parse('server url'));
        request.fields['user_id'] = UserId;
        request.fields['date_time'] = formatted;
        request.fields['current_address'] = address.text;
        if (filepath != null) {
          var stream =new http.ByteStream(DelegatingStream.typed(filepath.openRead()));
          var length = await filepath.length();
          var multipartFile = new http.MultipartFile(
              'location_image', stream, length,
              filename: path.basename(filepath.path));
          request.files.add(multipartFile);
        }
        var response = await request.send();
        print(response);
        if (response.statusCode == 200) {
          var response= await http.Response.fromStream(response);
          }
         }
      }'''''
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search