Flutter :- HTTP File Post Example: Image

半腔热情 提交于 2021-02-05 08:12:54

问题


Future userPasswordUpdate() async {

    String passwordU = password.text;
    String confirmPasswordU = confirmPassword.text;
    String oldPasswordU = oldPassword.text;

    var url = 'url';

    var response = await http.put(url,
        headers: {
          'Accept': 'application/json'
        },
        body: {
          "password": passwordU,
          "confirmPass": confirmPasswordU,
          "oldpassword": oldPasswordU,
        }
    );

I want to post image file to server with this method. But I Don't Know How. Can Anyone Help Me ?


回答1:


For the image upload you can also use the Dio library to post image on server with requested parameters.Please check the below example of it.

Dio dio = new Dio(); // with default Options

// Set default configs
    dio.options.baseUrl = BASE_URL;
    dio.options.connectTimeout = 5000; //5s
    dio.options.receiveTimeout = 3000;
    dio.options.headers[HEADER_AUTH_TOKEN_KEY] = HEADER_AUTH_TOKEN_VALUE;
    dio.options.headers[HEADER_VERSION_KEY] = HEADER_VERSION_VALUE;



    FormData formData = new FormData.fromMap({
      "password": passwordU,
      "confirmPass": confirmPasswordU,
      "oldpassword": oldPasswordU,


      "YOUR_IMAGE_PARAMETER_NAME": await MultipartFile.fromFile(imageFile.path,filename: imageFile.path.split("/").last),

    });

    var response = await dio.post(REGISTRATION_URL, data: formData);

    if (response.statusCode == 200) {
      apiResponse.onSuccess(response.toString(), eventType);
      print("Image Uploaded");
    } else {
      apiResponse.onError('Failed to load post');
      print("Upload Failed");
    }
  }

Inside the pubspec.yaml used this library,

dio: ^3.0.9

For the info about the library , you need to check this link Click



来源:https://stackoverflow.com/questions/61222440/flutter-http-file-post-example-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!