Flutter: How to convert URI to File?

Viewed 11712

I want to convert path "content://media/external/images/media/138501" to File and set in the Image.

Code:

File imageFile = File("content://media/external/images/media/138501");

is not working on:

DecorationImage(image: ExactAssetImage(imageFile.path),fit: BoxFit.fill)
6 Answers

You can use uri_to_file package. It supports content:// URI.

Simple to use (Updated)

import 'package:uri_to_file/uri_to_file.dart';

try {
  String uriString = 'content://sample.txt';

  // Don't pass uri parameter using [Uri] object via uri.toString().
  // Because uri.toString() changes the string to lowercase which causes this package to misbehave

  // If you are using uni_links package for deep linking purpose.
  // Pass the uri string using getInitialLink() or linkStream

  File file = await toFile(uriString);
} on UnsupportedError catch (e) {
  print(e.message);
} on IOException catch (e) {
  print(e);
} catch (e) {
  print(e);
}

then you can use this file as you want

Important note

Don't pass uri value like this

File file = await toFile(uri.toString());

Use like this if you are using uni_links package for deep linking purpose. Use getInitialLink() or linkStream

String? uriString = await getInitialLink();
if (uriString != null) {
  File file = await toFile(uriString);
}

linkStream.listen((uriString) async {
  if (uriString != null) {
    File file = await toFile(uriString!);
  }
});

This will not modify the uri string as we are not using uri.toString()

So this package will work fine

Working example: Working example

For more details: uri_to_file

According to the doc you can use the fromUri constructor: File.fromUri(Uri uri).

Your case:

File imageFile = File.fromUri("content://media/external/images/media/138501");

You could use Image.file constructor.

DecorationImage(
  image: Image.file(File("content://media/external/images/media/138501")),
  fit: BoxFit.fill
)

Please take a note: On Android, this may require the android.permission.READ_EXTERNAL_STORAGE permission.

You can use Absolute path plugin.

final filePath = await FlutterAbsolutePath.getAbsolutePath(uriString);

and then show the image by using Image.file:

Image.file(
    File(filePath),
);

Make use of flutter_absolute_path package. flutter_absolute_path: ^1.0.6 In pubsec.yaml


To convert file path from this format : “content://media/external/images/media/5275” To "/storage/emulated/0/DCIM/Camera/IMG_00124.jpg”

final filePath = await FlutterAbsolutePath.getAbsolutePath("Any path 
   here");

File tempFile = File(filePath);

    if (tempFile.existsSync()) {
      //add your logic here.
   }

define your URL:

final url = "Your Image Url";

then convert the Image Url to File in flutter :

XFile _xFile = XFile(url);

Done.

Related