DioError (DioError [DioErrorType.other]: Bad state: Can't finalize a finalized MultipartFile

1.5k Views Asked by At

I am attempting to upload multiple files using Dio, upon the request being sent I am receiving the error:

DioError (DioError [DioErrorType.other]: Bad state: Can't finalize a finalized MultipartFile.

My request is as follows:

Future<String> sendRequest() async {
    _className = classController.text;
    _studentName = studentController.text;
    _assnNum = assignmentController.text;
    if (_className != null && _studentName != null && _assnNum != null) {
      var url =
          "http://157.245.141.117:8000/uploadfile?collection=$_className&assn_num=$_assnNum&student_name=$_studentName";
      var uri = Uri.parse(url);
      var formData = FormData();
      for (var file in _files) {
        print('FilePath: ${file.path}');
        formData.files.addAll([
          MapEntry("assignment", await MultipartFile.fromFile(file.path)),
        ]);
        var response = await dio.post(
          url,
          data: formData,
          options: Options(headers: {
            HttpHeaders.contentTypeHeader: "application/x-www-form-urlencoded",
          }),
        );
        print(response.statusCode);
      }
    }

    return '';
  }

I am receiving a status on my api of 200, all params are being passed, but the files are not being uploaded. I'm not sure where to begin. I am uploading cpp files and python files, most examples I have found are dealing exclusively with images. I am unsure how to proceed.

1

There are 1 best solutions below

0
On

Avoid reusing finalized MultipartFile objects If you're reusing the same MultipartFile object for multiple requests, make sure to create a new instance for each request. Attempting to finalize a MultipartFile that has already been finalized can result in the error you're facing.

MultipartFile file = await MultipartFile.fromFile('path/to/file');

// Incorrect: Reusing the same MultipartFile object across requests
FormData formData1 = FormData.fromMap({
  'file1': file,
});

FormData formData2 = FormData.fromMap({
  'file2': file,
});

// Correct: Create a new MultipartFile instance for each request
MultipartFile file1 = await MultipartFile.fromFile('path/to/file1');
MultipartFile file2 = await MultipartFile.fromFile('path/to/file2');

FormData formData1 = FormData.fromMap({
  'file1': file1,
});

FormData formData2 = FormData.fromMap({
  'file2': file2,
});