flutterfile-uploadflutter-imageflutter-httpflutter-file

How to convert an Image instance to File instance in Flutter?


I am using VideoThumbanil class to fetch an Uint8List image of a video like this:

final uint8List = await VideoThumbnail.thumbnailData(video: videoFile.path,);

After doing so, i am converting the Uint8LIST to an Image using the following code:

Image image = Image.memory(uint8List);

What I want to do is to convert this image to a File class instance so that I can upload this image to my server. Code for uploading on server is:

void asyncFileUpload(File file) async {
  //create multipart request for POST or PATCH method
  var request = http.MultipartRequest("POST", Uri.parse("127.0.0.1/upload"));
  //create multipart using filepath, string or bytes
  var pic = await http.MultipartFile.fromPath("image", file.path);
  //add multipart to request
  request.files.add(pic);
  var response = await request.send();
  //Get the response from the server
  var responseData = await response.stream.toBytes();
  var responseString = String.fromCharCodes(responseData);
  print(responseString);
}

Solution

  • You can fetch the path to the temporary directory:

    final tempDir = await getTemporaryDirectory();
    

    After doing so, you can create a File in that temporary directory:

    File fileToBeUploaded = await File('${tempDir.path}/image.png').create();
    

    This way your file has a path and it's instance has been created. Now, you can write the file as:

    fileToBeUploaded.writeAsBytesSync(uint8List);
    

    Now, you can use fileToBeUploaded as File that is actually an image.

    Complete code:

    final uint8List = await VideoThumbnail.thumbnailData(video: videoFile.path,);
    final tempDir = await getTemporaryDirectory();
    File fileToBeUploaded = await File('${tempDir.path}/image.png').create();
    fileToBeUploaded.writeAsBytesSync(uint8List);
    asyncFileUpload(fileToBeUploaded);