0

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

  • How do you get the image? – Ozan Taskiran Sep 15 '22 at 20:57
  • `Future pickImage() async { XFile pickedImage = await singlePicker.pickImage( source: ImageSource.gallery, imageQuality: 10); if (pickedImage != null) { // singleImage = File(pickedImage.path); singleImage = pickedImage; bodies.add(MultipartBody('image',singleImage)); setState(() { }); } else { print('no image selected'); } }` was using this function to get the image. I fugured it out. Just had to pass 'Content-Type': 'application/json; charset=UTF-8', in headers and little bit tweaking for uploading images – Muhammad Abdullah Sep 15 '22 at 21:31

4 Answers4

1

You can use this code, it works perfectly

Future<String> uploadImage(String username,String password,File? image,String desc) async {

Map<String,String> body = {
  "username"          : username,
  "password"          : password,
  "desc"              : desc,
};

var response = http.MultipartRequest(
  "POST",
  Uri.parse("$dataURL/prescription"),
);
final httpImage = http.MultipartFile("image" , image!.readAsBytes().asStream(),image.lengthSync(),filename: image.path);

response.headers.addAll({'Content-type' : 'application/json' , 'Accept' : 'application/json'});
response.fields.addAll(body);
response.files.add(httpImage);

http.StreamResponse result = await response.send();

print("checkedUpload: ${result.statusCode}");

return await result.stream.bytesToString();

}

0

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?

Kevin Moore
  • 5,921
  • 2
  • 29
  • 43
0

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;
  }
Anaz
  • 112
  • 8
0

Add the image file using path

request.files.add(await http.MultipartFile.fromPath('image', filepath));

naveen_kc
  • 43
  • 4
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – primo Sep 21 '22 at 04:25