简体   繁体   中英

how to upload image to server using dio flutter

I want to upload an image from flutter to the server but I am failed. I tried with http package but it not worked. Then i found dio package useful and easy but I am getting following error when I use FormData .

the name 'FormData' is defined in the libraries 'package:dio/src/form_data.dart (via package:dio/dio.dart)' and 'package:get/get_connect/http/src/multipart/form_data.dart'. Try using 'as prefix' for one of the import directives, or hiding the name from all but one of the imports.

code


 static createNewSupervisor(String name, String email, String address,
      String site, String mobileNumber, String password, File? image) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var token = prefs.getString("token");
    var dio = Dio();
    var fd = FormData.fromMap({
      "full_name": name,
      "address": address,
      "mobile_no": mobileNumber,
      "email": email,
      "site_name": site,
      "password": password,
      // "image": baseimage,
    });
    var response = await dio.post("$baseURL/api/create",
        data: fd,
        options: Options(headers: {
          'Authorization': 'Bearer $token',
        } // set content-length
            ));
    print(response);
  }
tring mimeType = mime(fileName);
  String mimee = mimeType.split('/')[0];
  String type = mimeType.split('/')[1];

  Dio dio = new Dio();
  dio.options.headers["Content-Type"] = "multipart/form-data";
  FormData formData = new FormData.fromMap({
   'file':await MultipartFile.fromFile(filePath,
      filename: fileName, contentType: MediaType(mimee, type))
  });
  Response response = await dio
      .post('http://192.168.18.25:8080/test', data: formData)
      .catchError((e) => print(e.response.toString()));

The easiest method is to use the mime_type plugin from flutter.dev. Add this imports

Future<String> uploadingImage(File file) async {
  String fileName = file.path.split('/').last;
  FormData formData = FormData.fromMap({
   "file": await MultipartFile.fromFile(file.path, imageFile:imageFile),
  });
  response = await dio.post("/info", data: formData);
  return response.data['id'];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM