【问题标题】:How to get Image from URL to a File in Flutter?如何从 URL 获取图像到 Flutter 中的文件?
【发布时间】:2020-04-20 02:49:11
【问题描述】:

我在 Firebase 存储中保存了一张图片。如何将此图像文件的 URL 分配给文件?

有没有办法做到这一点:

File file = File(URL);

我也尝试过使用 http,但出现错误:'FileSystemException was throwresolving an image codec: Cannot open file'

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

使用 Uint8list 有有效数据,如下所示使用小部件时, 但与上述代码 File.fromRawPath(unint8list)

一起使用时会出错
Image.memory(uint8list);

尝试使用 ImageProvider 但无法从中获取 File 对象:

ImageProvider imageProvider = NetworkImage(url);

【问题讨论】:

  • 您是否尝试过从保存位置访问它?或者为什么不直接使用下载链接显示呢?
  • - 它保存在具有 URL 的 Firebase 存储上。 - 我无法使用 URL 显示它,因为如果需要,小部件还必须能够从本地存储中获取文件。更喜欢将其作为文件。
  • 您能解释一下您是如何下载图像的吗?你用了什么方法?你也说它给出了错误,请发布错误
  • 如上图我用过http,

标签: image file flutter


【解决方案1】:

设法获取 File 对象,必须以不同的方式使用 Uint8List,所以现在将使用它,这是工作代码:

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));

【讨论】:

    【解决方案2】:
    import 'dart:io';
    
    import 'package:uri_to_file/uri_to_file.dart';
    
    Future<void> convertUriToFile() async {
      try {
        String uriString = 'content://sample.txt'; // Uri string
    
        // 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); // Converting uri to file
      } on UnsupportedError catch (e) {
        print(e.message); // Unsupported error for uri not supported
      } on IOException catch (e) {
        print(e); // IOException for system error
      } catch (e) {
        print(e); // General exception
      }
    }
    

    【讨论】:

      【解决方案3】:

      试试像这样的东西

      Image.network('https://cdn.mos.cms.futurecdn.net/LEkEkAKZQjXZkzadbHHsVj-970-80.jpg')
      

      【讨论】:

      • 您的回答不适合提出的问题。您的答案是如何在颤振中使用 url 显示图像,但问题是如何从图像 url 获取文件。
      • 我认为它仍然是相关的,因为有些人可能只知道如何将图像显示为文件。因此他们可能会问自己如何将 URL 转换为文件。在这种情况下,答案非常有帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-10
      • 2018-02-20
      • 1970-01-01
      相关资源
      最近更新 更多