flutter 网络地址URL转file

方法1

c 复制代码
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';

Future<File> _fileFromImageUrl() async {
    final response = await http.get(Uri.parse('https://example.com/xyz.jpg)');

    final documentDirectory = await getApplicationDocumentsDirectory();

    final file = File(join(documentDirectory.path, 'imagetest.png'));

    file.writeAsBytesSync(response.bodyBytes);

    return file;
  }

方法2

c 复制代码
import 'dart:io';   
import 'package:dio/dio.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';


Future<File> getImage({required String url}) async {
  /// Get Image from server
  final Response res = await Dio().get<List<int>>(
    url,
    options: Options(
        responseType: ResponseType.bytes,
      ),
    );

    /// Get App local storage
    final Directory appDir = await getApplicationDocumentsDirectory();

    /// Generate Image Name
    final String imageName = url.split('/').last;

    /// Create Empty File in app dir & fill with new image
    final File file = File(join(appDir.path, imageName));

    file.writeAsBytesSync(res.data as List<int>);

    return file;
}

方法3

c 复制代码
Future<File> fileFromImageUrl() async {
String img='https://pps.whatsapp.net/v/t61.24694-24/160266256_1115367465775510_3546030680878251116_n.jpg?ccb=11-4&oh=01_AdSsrMGOPfs8CUJsEkYImMUu5L4DAzt2ym8eBrdsMG5O0Q&oe=63D7B45E';
    final response = await http.get(Uri.parse(img));

    final documentDirectory = await getApplicationDocumentsDirectory();

    final file =
        File(p.join(documentDirectory.path, 'File Name.jpg'));

    file.writeAsBytesSync(response.bodyBytes);

    return file;
  }
相关推荐
风华圆舞1 小时前
鸿蒙 + Flutter 下如何让 HarmonyOS 能力真正服务于 AI 体验
人工智能·flutter·harmonyos
BreezeDove3 小时前
【Android】Flutter3.35项目启动超时问题
android·flutter
风华圆舞3 小时前
鸿蒙 MICROPHONE 权限在 Flutter 项目里怎么处理
flutter·华为·harmonyos
愚者Pro17 小时前
切换本地 Flutter SDK 版本
flutter
TT_Close17 小时前
别再复制旧 Flutter 工程了,真正拖慢你的不是业务代码
flutter·npm·visual studio code
风华圆舞19 小时前
鸿蒙 + Flutter 下 AI 助手为什么要支持流式输出
人工智能·flutter·harmonyos
风华圆舞1 天前
鸿蒙 + Flutter 下 AI 页面的状态协同设计
人工智能·flutter·harmonyos
风华圆舞1 天前
鸿蒙语音播报功能 的 Flutter 侧封装思路
flutter·华为·harmonyos
brycegao3211 天前
Flutter 国际化富文本解决方案:基于双层占位符的轻量化图文混排方案
flutter·国际化·i18n·富文本·rtl·移动端工程架构
风华圆舞1 天前
鸿蒙 + Flutter 下美食探索场景为什么 AI 推荐比传统搜索更自然
flutter·harmonyos·美食