How to Upload a ScreenShot Image to Server using http Multipart FormData in Flutter?(Don't using base64 for image conversion )

Viewed 154

I want to upload a screenshot image to the server using Multipart FormData. But in my code, I save screenshots in the download folder, and this image I want to upload to the server.

I upload the screenshot to the server but the image path is not shown (Example https://beta.abc.com/storage/app/public/custom1648208518623daa86e84a6.) png or jpg type is not showing.

This is Response

{
  "success": true,
  "data": [
    {
      "download_image": "https:\/\/beta.abc.com\/storage\/app\/public\/user_download_image\/11\/custom\/custom1648208518623daa86e84a6.",
      "media_type": "image"
    }
  ],
  "message": "Download Image URL"
}
File? imgFile;
  Future<Uint8List?> _capturePngAndroid(int i) async {
    setState(() {
      downloaded = false;
    });
    try {
      RenderRepaintBoundary boundary =
      globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
      print('inside');
      ui.Image image = await boundary.toImage(pixelRatio: 3.0);

      ByteData? byteData;
      byteData = (await image.toByteData(format: ui.ImageByteFormat.png));

      var pngBytes = byteData!.buffer.asUint8List();
      File imgFile = File('');
      Directory directory;
      if (Platform.isAndroid) {
        if (await _requestPermission(Permission.storage)) {
          directory = (await getExternalStorageDirectory())!;
          String newPath = "";
          List<String> paths = directory.path.split("/");
          for (int i = 1; i < paths.length; i++) {
            String folder = paths[i];
            if (folder != "Android") {
              newPath += "/" + folder;
            } else {
              break;
            }
          }
          newPath = newPath + "/download/App/banner/custom";

          directory = Directory(newPath);
          print('direcyg$directory');
          print(pngBytes);

          if (!await directory.exists()) {
            await directory.create(recursive: true);
          }
          if (await directory.exists()) {
            //var FileName = "Custom"+"${i++}"+"$duration"+".png";
            // var FileName =
            //     "Custom"+ "$convertedDate" + ".png";
            var FileName =
                "Custom"+ ".png";
            Save.writeAsBytes(pngBytes);
            print("Save.path" + Save.path);

            imgFile = File('${directory.path}/$FileName');
            print("imgFile:->" + imgFile.path);
            uploadImage(imgFile.path);

          }
        }
      } else {
        if (await _requestPermission(Permission.photos)) {
          directory = await getTemporaryDirectory();
        }
      }
      setState(() {
        downloaded = true;
      });
      imgFile.writeAsBytes(pngBytes);
      Save = File(imgFile.path);


      print('Save $imgFile');
      setState(() {
        isLimitCharacter = false;
        downloaded = true;
        Navigator.push(context, MaterialPageRoute(
          builder: (context) {
            return DownloadImageScreen_custom(imgFile);
          },
        ));

        Fluttertoast.showToast(
            msg: 'File Downloaded ',
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.BOTTOM,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.white,
            textColor: splashGradientTwo,
            fontSize: 16.0);

        Fluttertoast.showToast(
            msg: imgFile.path,
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.BOTTOM,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.white,
            textColor: splashGradientTwo,
            fontSize: 16.0);
      });

      return pngBytes;
    } catch (e) {
      print(e);
      return null;
    }
  }




uploadImage(imagePath) async {
var request =http.MultipartRequest("POST",Uri.parse(customDownloadImage));


    SharedPreferences prefs = await SharedPreferences.getInstance();
    var tokens = prefs.getString("token") ?? '';
    print('Upload Tokens ==>$tokens');
    request.headers['Authorization'] = 'Bearer $tokens';

    //add text fields
    request.fields["media_type"] = "image";

    //create multipart using filepath, string or bytes
    print("Upload Request Field ==>" + request.fields.toString());
    // if(imageFile!=null) {

    var pic = await http.MultipartFile.fromBytes(
        "documents", File(imagePath).readAsBytesSync(),
        filename: imagePath.split("/").last);

    //add multipart to request
    request.files.add(pic);
    //}

    print("Upload Request image_path ==>" + imagePath);

    print("Upload Request" + request.toString());

    var response = await request.send();
    print("Upload Response" + response.toString());

    //Get the response from the server
    var responseData = await response.stream.toBytes();
    print("Upload Response Data" + responseData.toString());
    var uploadJsonData = jsonDecode(responseData.toString());
    print("Upload Response JsonData" + uploadJsonData.toString());

    var responseString = String.fromCharCodes(responseData);
    print("Upload Response String" + responseString.toString());

    if (response.statusCode == 200) {
      print("--------------------Success Image Uploaded---------------");
      return true;
    } else {
      print("--------------------Unable to upload image---------------");
    }
  }
0 Answers
Related