김민진
김민진

Reputation: 59

how to use flutter dio connect-type multipart?

my code here

Dio dio = new Dio();
    String fileName = event.file!.path.split('/').last;
    FormData formData = FormData.fromMap({
      "file":
          await MultipartFile.fromFile(event.file!.path, filename: fileName),
    });
    try {
      var response = await dio.post(
        "url",
        data: formData,
        options: new Options(
          contentType: "multipart/form-data",
            headers: {
              "token": await getToken(),
              // "Content-Type": "multipart/form-data"
            }),
        // headers: {"token": "test:1234"}),
      );
    }
    catch (e){
      print(e);
    }

my error version 1

error type. DioErrorType.other
error : SocketException : OS Error Connection refused,errorno=61 

and my error version 2

error type. DioErrorType.response
error : Http status error[400]

my requestOptions here

method = "POST"
_defaultContentType = "multipart/form-data"

How can I hand over the file to the server? The problem I think is that the content-type is not suitable, so there seems to be an error.

Upvotes: 0

Views: 1846

Answers (1)

Jared Anderton
Jared Anderton

Reputation: 1026

I have a similar implementation. I also use Dio, though in my code, I have it abstracted away with _api.

Future<Response> uploadLogo({@required File file}) async {
  String fileName = file.path.split('/').last;
  FormData formData = FormData.fromMap({"file": await MultipartFile.fromFile(file.path, filename:fileName) });
  return await _api.post(url: url, data: formData);
}

Note that I don't even set the content type. I suspect that Dio looks at the type of object in the data parameter, and handles the appropriate headers/encoding under the hood.

Also, if you have having the content-type set to something unexpected, I'd recommend checking if you are using any RequestInterceptor's. I was, and had to write an exception, because I was setting it correctectly, by my RequestInterceptor was overriding it, (because all of my other endpoints wanted JSON):

class RequestInterceptor extends InterceptorsWrapper {

  @override
  void onRequest(RequestOptions options, handler) {
    if(!options.headers.containsKey('content-type')) {
      options.headers['content-type'] = 'application/json';
    }
    // ...
    super.onRequest(options, handler);
  }

}

Upvotes: 1

Related Questions