3

I'm facing a problem from the server I'm getting the image url data as a string. I need to save all these urls in the XFile format list. Tell me how can I convert the image url to XFile format?

I get

enter image description here

2
  • you mean you want to download images from network links, to local device then use them with their own paths in XFile ? Commented Nov 15, 2022 at 17:57
  • Yes. I am getting an image url from the web and this image needs to be converted to XFile format. Commented Nov 15, 2022 at 17:59

2 Answers 2

6

Try this:

static Future<XFile> getImageXFileByUrl(String url) async {
    var file = await DefaultCacheManager().getSingleFile(url);
    XFile result = await XFile(file.path);
    return result;
  }
Sign up to request clarification or add additional context in comments.

Comments

1

Anyone can try this code if you also need the mime type or actual file extension,

Need 2 packages path_provider and mime.

import 'package:http/http.dart' show get;

  Future<XFile> getImageXFileByUrl(String url) async {
    Directory tempDir = await getTemporaryDirectory();
    String tempPath = tempDir.path;
    String fileName = "image${DateTime.now().millisecondsSinceEpoch}";
    File fileWrite = new File("$tempPath/$fileName");
    Uri uri = Uri.parse(url);
    final response = await get(uri);
    fileWrite.writeAsBytesSync(response.bodyBytes);
    final mimeType = lookupMimeType("$tempPath/$fileName", headerBytes: [0xFF, 0xD8]);
    final type = mimeType.split("/");
    final file = XFile("$tempPath/$fileName", mimeType: mimeType);
    return file;
  }

headerBytes: [0xFF, 0xD8] was found on the mime readme file.

enter image description here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.