You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何从API的BLOB响应下载并保存文件?

在Flutter中处理BLOB响应并下载保存文件

核心流程说明

从API获取BLOB二进制数据后,将其写入本地文件即可完成下载,以下是具体实现步骤:


1. 依赖准备

在pubspec.yaml中添加所需依赖:

dependencies:
  flutter:
    sdk: flutter
  http: ^1.2.1          # 发起HTTP请求
  path_provider: ^2.1.2 # 获取本地存储路径
  permission_handler: ^11.3.1 # 请求存储权限(安卓/iOS)
  open_file: ^3.3.2    # 可选,用于打开下载后的文件

执行flutter pub get完成依赖安装。


2. 获取BLOB二进制数据

发起API请求时,直接获取响应的bodyBytes(原始二进制字节),无需解析JSON:

import 'package:http/http.dart' as http;

Future<List<int>> fetchBlobData() async {
  final response = await http.get(
    Uri.parse('你的目标API地址'),
    // API需要认证时添加请求头
    headers: {'Authorization': 'Bearer 你的认证Token'},
  );

  if (response.statusCode == 200) {
    return response.bodyBytes; // 返回BLOB的原始二进制数据
  } else {
    throw Exception('请求失败,状态码:${response.statusCode}');
  }
}

3. 请求存储权限(必要)

安卓和iOS都需要存储权限才能写入文件,用permission_handler实现:

import 'package:permission_handler/permission_handler.dart';

Future<bool> requestStoragePermission() async {
  var status = await Permission.storage.status;
  if (!status.isGranted) {
    status = await Permission.storage.request();
  }
  return status.isGranted;
}

4. 将BLOB数据写入本地文件

使用path_provider获取应用可访问的存储目录,再通过File类写入字节:

import 'dart:io';
import 'package:path_provider/path_provider.dart';

Future<File> saveBlobToFile(List<int> blobBytes, String fileName) async {
  // 获取应用私有文档目录(无需额外权限即可访问)
  final directory = await getApplicationDocumentsDirectory();
  final filePath = '${directory.path}/$fileName';
  final file = File(filePath);

  // 将二进制字节写入文件
  await file.writeAsBytes(blobBytes);
  return file;
}

提示:从你提供的BLOB内容看,这是FlateDecode压缩的PDF流,保存时文件名后缀建议设为.pdf,确保后续能正确打开。


5. 整合完整流程(下载+可选打开文件)

把上述步骤整合,实现完整的下载逻辑:

import 'package:open_file/open_file.dart';

Future<void> downloadAndHandleFile() async {
  // 1. 请求存储权限
  bool hasPermission = await requestStoragePermission();
  if (!hasPermission) {
    // 处理权限拒绝的情况,比如提示用户开启权限
    return;
  }

  try {
    // 2. 获取BLOB数据
    List<int> blobData = await fetchBlobData();

    // 3. 保存文件
    File savedFile = await saveBlobToFile(blobData, 'downloaded_document.pdf');

    // 4. 可选:打开下载后的文件
    await OpenFile.open(savedFile.path);
  } catch (e) {
    // 处理异常,比如网络错误、文件写入失败等
    print('下载失败:$e');
  }
}

大文件优化方案

如果BLOB是大文件,建议用流式下载避免内存溢出,可使用dio库实现:

import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';

Future<void> downloadLargeBlobFile() async {
  final dio = Dio();
  final directory = await getApplicationDocumentsDirectory();
  String savePath = '${directory.path}/large_document.pdf';

  await dio.download(
    '你的API地址',
    savePath,
    // 监听下载进度
    onReceiveProgress: (received, total) {
      if (total != -1) {
        print('下载进度:${(received / total * 100).toStringAsFixed(0)}%');
      }
    },
    // 添认证头(如果需要)
    options: Options(headers: {'Authorization': 'Bearer 你的Token'}),
  );

  // 下载完成后打开文件
  await OpenFile.open(savePath);
}

内容的提问来源于stack exchange,提问作者Jaimin Modi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 19:07:19