Загрузить выбранное изображение в API во Flutter, используя плагин выбора изображений - PullRequest
0 голосов
/ 22 марта 2020

Я хочу загрузить изображение в API. Я попробовал этот код, но получил ошибку

Файл не найден

Если я отправляю файл изображения с помощью Postman, он успешно работает. Здесь я приложил скриншот Почтальона, для загрузки изображения, которое я дал image path, и в дополнение к моему документу, я хочу прикрепить пользователя id, пожалуйста, скажите мне решение? спасибо

Это мой код

class _UserProfileEditState extends State<UserProfileEdit> {
  // String imagepath='';
  File _profileImage;
  String base64Image;
  DatabaseHelper databaseHelper = new DatabaseHelper();

  int parentid;

  _handleimagefromgallary() async {
    File imagefile = await ImagePicker.pickImage(source: ImageSource.gallery);

    if(imagefile!=null) {
      setState(() {
        _profileImage = imagefile;
      });
    }
 }

 _displayprofilephoto()
 {
    if(_profileImage==null)
    {
      if(widget.parentsInfo.data.photo==null)
      {
        return AssetImage('assets/images/parentimg.png');
      }
      else
      {
        return CachedNetworkImageProvider(widget.parentsInfo.data.photo);
      }
    }
    else
    {
      return FileImage(_profileImage);
    }
  }

@override
  Widget build(BuildContext context) {

     parentid=widget.parentsInfo.data.id;

    return Scaffold(
      appBar: AppBar(
        title: Center(
          child: Text('Edit Profile'),
        ),
      ),
      body: SingleChildScrollView(
          child: Container(
        height: MediaQuery.of(context).size.height * 1.5,
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Center(
                child: Container(
                  height: 160.0,
                  width: 160.0, //MediaQuery.of(context).size.width,
                  child: new CircleAvatar(
                    radius: 50.0,
                    backgroundColor: Colors.green,
                    backgroundImage: _displayprofilephoto(),
                  ),
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(''),
                  InkWell(
                    child: Icon(Icons.add_photo_alternate),
                    onTap:_handleimagefromgallary,
                  ),
                ],
              ),
            ),

            showpdatebutton(),

Это способ загрузки:

Future _updateprofilepicture() async{
   // _profileImage=await FlutterAbsolutePath.getAbsolutePath(images[i].identifier);
    // var path = await FlutterAbsolutePath.getAbsolutePath(images[i].identifier);
   // var path =await FlutterAbsolutePath.getAbsolutePath(_profileImage.absolute.path);

    var path=await FlutterAbsolutePath.getAbsolutePath(_profileImage.path);

    if(path==null)
      {

      }
    else
      {
          // call controller
        print(path);
        String id=parentid.toString();
        databaseHelper.parentprofileupdate(path, id);
     //   databaseHelper.parentprofileupdate(_profileImage, id);
      }


  }

  Widget showpdatebutton() {
    if(_profileImage!=null)
      {
        return OutlineButton(
            child: Text('Update Profile Picture'),
            onPressed: (){
              _updateprofilepicture();
            }
        );
      }
    else
      {
        return Container();
      }
  }

}

Мой класс помощника по базе данных:

Future<ParentProfileUpdate> parentprofileupdate(String path,String id) async
    {

      Map mapValue;
      var data;

      final prefs = await SharedPreferences.getInstance();
      final key = 'token';
      final value = prefs.get(key ) ?? 0;



      String myUrl = "$serverUrl/api/v1/upload_parent_image";
      await  http.post(myUrl,
          headers: {

           // 'Accept':'application/json',
            "HttpHeaders.contentTypeHeader": "application/json",
            'Authorization' : 'Bearer $value'

          },
          body: {
                    "photo" :path,
                      "id":id,

          }).then((response) {

        status = response.body.contains('error');
        mapValue=json.decode(response.body);
        var data = json.decode(response.body);

        print(data);

      });
    }

postman http request body

...