How to get Image from URL to a File in Flutter?

5,738

Managed to get the File object, had to use Uint8List in a different way, so will use it for now, here is the working code:

final http.Response responseData = await http.get(strURL);
uint8list = responseData.bodyBytes;
var buffer = uint8list.buffer;
ByteData byteData = ByteData.view(buffer);
var tempDir = await getTemporaryDirectory();
File file = await File('${tempDir.path}/img').writeAsBytes(
    buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
Share:
5,738
Ant D
Author by

Ant D

Updated on December 16, 2022

Comments

  • Ant D
    Ant D over 1 year

    I have an image saved on Firebase Storage. How can I assign this URL of the image file to a File?

    Is there some way to do it as:

    File file = File(URL);
    

    I've also tried using http, but results in an error : 'FileSystemException was thrown resolving an image codec: Cannot open file'

    final http.Response responseData = await http.get(url);
    Uint8List uint8list = responseData.bodyBytes;
    File file = File.fromRawPath(uint8list);
    

    Using Uint8list has valid data, as seen when using widget shown below, but gives an error when used with above code, File.fromRawPath(unint8list)

    Image.memory(uint8list);
    

    Tried using ImageProvider but can't get a File object from it:

    ImageProvider imageProvider = NetworkImage(url);
    
    • Henok
      Henok over 4 years
      have you tried to access it from where its saved ? or why not display it directly using the download link ?
    • Ant D
      Ant D over 4 years
      - It is saved on Firebase Storage, which has a URL. - I cannot display it using the URL because the widget has to also be able to get the file from local storage if required. Prefer having it as a file.
    • Henok
      Henok over 4 years
      can you explain how you downloaded the image ? what method you have used ?and also you said it gives error, please post the error
    • Ant D
      Ant D over 4 years
      As shown above I've used http,
  • AzeTech
    AzeTech about 3 years
    Your answer is inappropriate to question asked. your answer is how to show image using url in flutter, but question is how to get file from image url.
  • Paul
    Paul over 2 years
    I think it is still relevant, as some people might only know how to display images as files. Therefore they might ask themselves how to convert URL to file. In that case, the answer is very helpful.