如何在Flutter应用中使用BunnyCDN加载、下载及上传图片
在Flutter中使用BunnyCDN处理图片的完整方案
一、加载图片
BunnyCDN的图片加载逻辑和普通网络图片一致,只需拿到图片的BunnyCDN公开访问链接,用Flutter自带的Image.network()组件即可实现:
Image.network( 'https://你的存储区标识.b-cdn.net/图片存储路径/xxx.jpg', // 可选:添加加载状态、错误处理 errorBuilder: (context, error, stackTrace) => const Icon(Icons.error_outline), loadingBuilder: (context, child, loadingProgress) { if (loadingProgress == null) return child; return CircularProgressIndicator( value: loadingProgress.expectedTotalBytes != null ? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes! : null, ); }, )
如果需要图片优化,可直接在URL后拼接BunnyCDN支持的参数:
- 压缩质量:
?quality=75 - 调整尺寸:
?width=400&height=300 - 格式转换:
?format=webp
二、下载图片到本地
可以借助dio和path_provider包实现,步骤如下:
- 在
pubspec.yaml添加依赖:
dependencies: dio: ^5.0.0 path_provider: ^2.0.0
- 实现下载逻辑:
import 'dart:io'; import 'package:dio/dio.dart'; import 'package:path_provider/path_provider.dart'; Future<void> downloadBunnyImage(String imageUrl) async { final dio = Dio(); final appDocDir = await getApplicationDocumentsDirectory(); final savePath = '${appDocDir.path}/saved_image.jpg'; try { await dio.download( imageUrl, savePath, onReceiveProgress: (received, total) { if (total != -1) { print('下载进度:${(received / total * 100).toStringAsFixed(0)}%'); } }, ); print('图片已保存至:$savePath'); } catch (e) { print('下载失败:$e'); } }
三、上传图片到BunnyCDN
通过BunnyCDN的存储API实现上传,需要用到你的存储区API密钥和存储区名称:
- 确保已添加
dio依赖(同上); - 编写上传代码:
import 'package:dio/dio.dart'; Future<void> uploadToBunnyCDN(String localImagePath) async { final dio = Dio(); final apiKey = '你的存储区API密钥'; final storageZone = '你的存储区名称'; final uploadUrl = 'https://storage.bunnycdn.com/$storageZone/目标存储路径/xxx.jpg'; try { final formData = FormData.fromMap({ 'file': await MultipartFile.fromFile(localImagePath), }); await dio.post( uploadUrl, data: formData, options: Options( headers: {'AccessKey': apiKey}, ), ); print('图片上传成功'); } catch (e) { print('上传失败:$e'); } }
注意事项:
- 目标存储路径若不存在,BunnyCDN会自动创建;
- API密钥可在BunnyCDN后台的存储区设置中获取,请勿泄露;
- 大文件上传可扩展分块上传逻辑,BunnyCDN官方支持该功能。
内容的提问来源于stack exchange,提问作者Ariyo
相关产品推荐
相关产品推荐

