Flutter文件上传插件uploadthing的使用
Flutter文件上传插件uploadthing的使用
UploadThing Dart SDK
一个非官方的Dart/Flutter SDK,用于UploadThing API,提供无缝的文件上传功能。此包允许你通过UploadThing服务轻松地将文件上传功能集成到你的Dart或Flutter应用程序中。
特性
- 轻松上传单个或多个文件。
- 跟踪上传进度并管理文件数据。
- 支持各种文件类型和操作,如重命名和删除文件。
- 检索和显示应用信息和使用统计。
使用方法
导入包
import 'package:uploadthing/uploadthing.dart';
import 'dart:io';
初始化和上传文件
void main() async {
// 使用你的实际API密钥替换
final uploadThing = UploadThing('YOUR_API_KEY');
// 文件列表
List<File> files = [
File('path/to/file1.jpg'),
File('path/to/file2.png'),
];
try {
// 执行文件上传
bool isUploaded = await uploadThing.uploadFiles(files);
if (isUploaded) {
print('Files uploaded successfully');
print('Uploaded Files Data: ${uploadThing.uploadedFilesData}');
}
} catch (e) {
print('Upload failed: $e');
}
}
跟踪上传进度
print('Uploaded ${uploadThing.uploadedFiles} of ${uploadThing.totalFiles} files');
访问上传的文件数据
for (var fileData in uploadThing.uploadedFilesData) {
print('File URL: ${fileData['url']}');
}
API参考
类
UploadThing
处理文件上传和与UploadThing API交互的主要类。
- 构造函数:
UploadThing(String apiKey)
- 初始化实例并传入API密钥。
方法
-
Future<bool> uploadFiles(List<File> files)
- 上传文件列表到API。
- 参数:
files
:File
对象列表。
- 返回值: 成功时返回
true
,否则抛出Exception
。
-
Future<List<UploadThingFile>> listFiles({int limit = 500, int offset = 0})
- 获取已上传文件列表。
- 参数:
limit
: 最大文件数(默认为500)。offset
: 跳过的文件数。
- 返回值:
UploadThingFile
对象列表。
-
Future<bool> renameFile(String fileKey, String newName)
- 在服务器上重命名文件。
- 参数:
fileKey
: 文件标识符。newName
: 新文件名。
- 返回值: 成功时返回
true
,否则抛出Exception
。
-
Future<bool> renameFiles(List<Map<String, String>> updates)
- 重命名多个文件。
- 参数:
updates
: 包含文件键和新名称的映射列表。
- 返回值: 成功时返回
true
,否则抛出Exception
。
-
Future<bool> deleteFile(String fileKey)
- 删除文件。
- 参数:
fileKey
: 文件标识符。
- 返回值: 成功时返回
true
,否则抛出Exception
。
-
Future<bool> deleteFiles(List<String> fileKeys)
- 删除多个文件。
- 参数:
fileKeys
: 文件标识符列表。
- 返回值: 成功时返回
true
,否则抛出Exception
。
-
Future<AppInfo> getAppInfo()
- 获取应用程序信息。
- 返回值: 包含应用程序详细信息的
AppInfo
对象。
-
String getFileUrl(String key)
- 根据文件键获取文件URL。
- 参数:
key
: 文件唯一标识符。
- 返回值: 构建的文件URL。
-
Future<UsageInfo> getUsageInfo()
- 获取应用程序使用情况信息。
- 返回值: 包含使用统计信息的
UsageInfo
对象。
类详情
AppInfo
包含应用程序信息。
- 属性:
appId
: 应用程序ID。defaultACL
: 默认访问控制列表。allowACLOverride
: 是否允许ACL覆盖。
UploadThingFile
表示上传到UploadThing的文件。
- 属性:
id
: 文件ID。key
: 文件唯一标识符。name
: 文件名。customId
: 文件自定义标识符。status
: 文件状态。
UsageInfo
提供应用程序使用统计信息。
- 属性:
totalBytes
: 总字节数。appTotalBytes
: 应用程序使用的总字节数。filesUploaded
: 已上传文件数量。limitBytes
: 应用程序字节限制。
示例用法
上传多个文件
void main() async {
final uploadThing = UploadThing('YOUR_API_KEY');
List<File> files = [
File('path/to/file1.jpg'),
File('path/to/file2.png'),
];
try {
bool isUploaded = await uploadThing.uploadFiles(files);
if (isUploaded) {
print('Files uploaded successfully');
}
} catch (e) {
print('Upload failed: $e');
}
}
列出文件
void listFiles() async {
final uploadThing = UploadThing('YOUR_API_KEY');
try {
List<UploadThingFile> files = await uploadThing.listFiles(limit: 10);
files.forEach((file) {
print('File: ${file.name}, Status: ${file.status}');
});
} catch (e) {
print('Error: $e');
}
}
重命名文件
void renameFileExample() async {
final uploadThing = UploadThing('YOUR_API_KEY');
try {
bool response = await uploadThing.renameFile("exampleKey", "newName.jpg");
if (response) {
print('File renamed successfully');
}
} catch (e) {
print('Error: $e');
}
}
删除文件
void deleteFileExample() async {
final uploadThing = UploadThing('YOUR_API_KEY');
try {
bool response = await uploadThing.deleteFile("exampleKey");
if (response) {
print('File deleted successfully');
}
} catch (e) {
print('Error: $e');
}
}
更多关于Flutter文件上传插件uploadthing的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter文件上传插件uploadthing的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用uploadthing
(假设这是一个假想的文件上传插件,因为实际上没有一个名为uploadthing
的广泛使用的Flutter插件)进行文件上传的代码示例。由于uploadthing
是一个虚构的插件,我会用类似功能的插件flutter_uploader
作为替代来展示如何实现文件上传功能。
首先,确保在你的pubspec.yaml
文件中添加flutter_uploader
依赖:
dependencies:
flutter:
sdk: flutter
flutter_uploader: ^x.y.z # 请替换为最新版本号
然后,运行flutter pub get
来安装依赖。
接下来,我们创建一个简单的Flutter应用来演示文件上传。
1. 初始化上传配置
在你的Flutter项目的main.dart
文件中,初始化flutter_uploader
的配置:
import 'package:flutter/material.dart';
import 'package:flutter_uploader/flutter_uploader.dart';
void main() {
// 初始化上传配置
configureUploader(
baseUrl: "https://your-server.com/upload", // 替换为你的服务器URL
headers: <String, String>{
'Authorization': 'Bearer YOUR_ACCESS_TOKEN', // 如果需要认证,添加认证头
},
maxConcurrentTasks: 3, // 同时上传的最大任务数
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: UploadPage(),
);
}
}
2. 创建上传页面
创建一个UploadPage
页面,允许用户选择文件并上传:
import 'package:flutter/material.dart';
import 'package:flutter_uploader/flutter_uploader.dart';
import 'dart:io';
class UploadPage extends StatefulWidget {
@override
_UploadPageState createState() => _UploadPageState();
}
class _UploadPageState extends State<UploadPage> {
final uploader = FlutterUploader();
Future<void> pickFile() async {
FilePickerResult result = await FilePicker.platform.pickFiles(
type: FileType.any,
allowMultiple: false,
);
if (result.files.isNotEmpty && result.files.first.isNotEmpty) {
File file = File(result.files.first.path!);
uploadFile(file);
}
}
void uploadFile(File file) {
var uploadTask = uploader.upload(
filePath: file.path,
url: "/upload", // 服务器上的上传路径(相对于baseUrl)
method: UploadHTTPMethod.post,
headers: <String, String>{
'Content-Type': 'multipart/form-data',
},
data: <String, String>{
'file_description': 'This is a test file',
},
tag: file.path, // 用于标识上传任务的唯一标签
);
uploadTask.onProgress((progress) {
print("Upload Progress: ${progress.progress}%");
});
uploadTask.onComplete((response, error) {
if (response != null) {
print("Upload Success: ${response.responseBody}");
} else {
print("Upload Error: ${error}");
}
});
uploadTask.onError((error, errorMessage) {
print("Upload Error: ${errorMessage}");
});
uploadTask.onCancel((cancelMessage) {
print("Upload Cancelled: ${cancelMessage}");
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('File Upload'),
),
body: Center(
child: ElevatedButton(
onPressed: pickFile,
child: Text('Pick a file and upload'),
),
),
);
}
}
3. 权限处理
如果你的应用需要访问文件系统,你还需要在AndroidManifest.xml
和Info.plist
中添加必要的权限。
Android (AndroidManifest.xml
)
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
iOS (Info.plist
)
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>NSPhotoLibraryUsageDescription</key>
<string>App needs access to photo library</string>
<key>NSCameraUsageDescription</key>
<string>App needs access to camera</string>
<key>NSMicrophoneUsageDescription</key>
<string>App needs access to microphone</string>
请注意,实际项目中你可能需要更精细地处理权限请求,特别是在iOS上。
以上代码示例展示了如何使用flutter_uploader
插件在Flutter应用中进行文件上传。如果你确实在寻找一个名为uploadthing
的插件,建议查阅其官方文档或GitHub仓库以获取具体的使用说明。