Home > OS >  How to submit data without image using MultipartRequest?
How to submit data without image using MultipartRequest?

Time:04-19

I want to submit form data without taking image.

My user can select an image or without choosing any image they can submit data. I have this for taking an image

Future cameraImage() async {
    var pickedImage = await _picker.pickImage(
        source: ImageSource.camera,
    );
    if (pickedImage != null) {
      setState(() {
        _image = File(pickedImage.path);
      });
    }
    else {
      setState(() {
        _image = Image.asset('assets/kids.png') as File?;
      });
    }
  }

and here is my Post Method.

Future uploadImage() async {
    final uri =
        Uri.parse(Constant.AddStory);
    var request = http.MultipartRequest("POST", uri);
    request.fields['storyTitle'] = _ttlController.text;
    request.fields['userId'] = this.widget.userId.toString();
    var pic = await http.MultipartFile.fromPath('storyImage', _image!.path);
    request.files.add(pic);

    var response = await request.send();

    if (response.statusCode == 200) {
      print('Image uploaded');
      Navigator.pop(context);
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => HomePage(),
        ),
      );
    } else {
      print("Failed to upload");
      print(response);
    }
  }

CodePudding user response:

You can hAndle it by creating two separate Uploadwithimage() and uploadwithoutimage()

(_image== null) ?uploadwithoutimage ():uploadwithimage();
  • Related