Home > Mobile >  I am unable to upload an image to the backend using http and image picker for flutter web
I am unable to upload an image to the backend using http and image picker for flutter web

Time:09-16

Here is my function for uploading to the server using http . I have tried to convert the image to a base64 string but still the issue persists

uploadImage() async {

var postUri = Uri.parse('${xyz}/api/v1/listing/store');
var request = new http.MultipartRequest("POST", postUri);
request.fields['name'] = titleTEC.text.toString();
request.fields['category_id'] = selectedCategoryId.toString();
request.fields['price'] = priceTEC.text.toString();
request.fields['discount'] = 2.toString();
request.fields['discount_type'] = 'percent';
request.headers['moduleId'] = 2.toString();
Uint8List _list = await singleImage.readAsBytes();
request.files.add(http.MultipartFile(
  'image', singleImage.readAsBytes().asStream(), _list.length,
  filename: '${DateTime.now().toString()}.png',
));

// request.files.add(new http.MultipartFile.fromString('image', base64Image));

request.send().then((response) {

  print(response.statusCode);
});

}

This is the error i get when I hit the functions p.s. I am specifically using flutter web

CodePudding user response:

Looking at the stack trace, it seems that you're calling into dart:io code, that is NOT supported on the web. Are you sure the sixam_mart code is designed to work in the browser?

CodePudding user response:

use dio package, it is also used for api calls and its so effective.

  Future updateProfilePicApi(File profilepic) async {
    dynamic responseJson;
    try {
      var dio = Dio();
     
      String fileName = profilepic.path.split('/').last;
      FormData formData = FormData.fromMap({
        
        "image":
            await MultipartFile.fromFile(profilepic.path, filename: fileName),
      });

      var response = await dio.post('${xyz}/api/v1/listing/store',
          options: Options(
              headers: {
                'Accept': 'application/json',
                
              },
              followRedirects: false,
              validateStatus: (status) {
                return status! <= 500;
              }),
          data: formData);
      print("::::::::::::::::status code::::::::::::::");
      print(response.statusCode);
      responseJson = response.data;
    } on SocketException {
      print("no internet");
    }
    return responseJson;
  }
  • Related