Cannot upload image using dio post request

Viewed 429

I am trying to upload a photo with caption to REST API. But since it is my first time, I am getting some exceptions. My code for uploading the image is shown below:

Dio dio = new Dio();

      dio.options.headers['content-Type'] = 'multipart/form-data';
      dio.options.headers['Authorization'] = 'Token ${box.get('token')}';

      FormData formData = FormData.fromMap({
        "author": box.get('user_id'),
        "description": _caption,
        "image": MultipartFile.fromFileSync(_image.path,
            filename: _image.path.split(Platform.pathSeparator).last)
      });

      dio
          .post("$baseURL/posts/create/",
              data: formData,
              options:
                  Options(method: 'POST', responseType: ResponseType.plain))
          .then((response) => print(response))
          .catchError((error) => print(error));

After I run this on my device and try to upload image, it directs me to dio.dart package line throw assureDioError(e, options);

If you have any knowledge with uploading images using dio, kindly help solve it.

UPDATED: body of json

{
    "author": null,
    "description": "",
    "image": null
}

UPDATED: I tried with another service uploading image (not dio)

// string to uri
      var uri = Uri.parse("$baseURL/posts/create/");

      // create multipart request
      var request = http.MultipartRequest("POST", uri);

      // add headers with Auth token
      Map<String, String> headers = {
        "Authorization": "Token ${box.get('token')}",
        "Content-type": "multipart/form-data"
      };

      request.headers.addAll(headers);

      // add fields
      Map<String, String> fields = {
        'author': box.get('user_id').toString(),
        'description': _caption,
      };

      request.fields.addAll(fields);

      // multipart that takes file
      var multipartFile = http.MultipartFile(
        'file',
        _image.readAsBytes().asStream(),
        _image.lengthSync(),
        filename: _image.path.split('/').last,
        contentType: MediaType('image', 'jpeg'),
      );

      // add file to multipart
      request.files.add(multipartFile);
      print(request.toString());

      // send
      var response = await request.send();
      print(response.statusCode);

      // listen for response
      response.stream.transform(utf8.decoder).listen((value) {
        print(value);
      });

I have tried uploading images with the above code as well. But this returns me the error saying "image":["No file was submitted."]

0 Answers
Related