Flutter文件流上传插件gotipath_stream_uploader的使用

Flutter文件流上传插件gotipath_stream_uploader的使用

安装

pubspec.yaml文件的dependencies部分添加以下依赖:

gotipath_stream_uploader: ^1.0.1

或者使用最新版本。

使用

在将要使用的.dart文件中添加以下导入语句:

import 'package:gotipath_stream_uploader/gotipath_stream_uploader.dart';

示例

以下是一个完整的示例代码,展示了如何使用gotipath_stream_uploader插件进行文件流上传:

import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:gotipath_stream_uploader/gotipath_stream_uploader.dart';
import 'package:image_picker/image_picker.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'UpChunk Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'UpChunk Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({this.title = ''});

  final String title;

  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // 添加端点和凭证
  final String _endPoint = "https://apistream.gotipath.com/v1/";
  final String _clientID = 'Your client ID';
  final String _libraryID = 'Your library ID';
  final String _apiKey = 'Your API key';
  String _videoID = '';

  final picker = ImagePicker();

  int _progress = 0;
  bool _uploadComplete = false;
  String _errorMessage = '';

  String fileToUpload = '';
  GotipathStreamUploader gotipathStreamUploader = GotipathStreamUploader();

  void _getFile() async {
    fileToUpload = '';
    final pickedFile = await picker.pickVideo(source: ImageSource.gallery);

    if (pickedFile == null) return;

    setState(() {
      fileToUpload = pickedFile.path;
    });

    final videoID = await createUploadUrlRequest(
      endPoint: _endPoint,
      clientID: _clientID,
      libraryID: _libraryID,
      apiKey: _apiKey,
    );
    _videoID = videoID;
  }

  Future<String> createUploadUrlRequest({
    String? endPoint,
    String? clientID,
    String? libraryID,
    String? apiKey,
  }) async {
    final String url = '$endPoint/libraries/$libraryID/videos';
    final client = http.Client();

    try {
      final response = await client.post(
        Uri.parse(url),
        headers: {
          'Accept': 'application/json',
          'Content-type': 'application/json',
          "X-Auth-ClientId": clientID!,
          "X-Auth-LibraryId": libraryID!,
          "X-Auth-ApiKey": apiKey!
        },
        body: jsonEncode(<String, String>{
          'name': fileToUpload.split('/').last,
        }),
      );

      if (response.statusCode == 200) {
        return jsonDecode(response.body)['result']['id'];
      } else {
        return "";
      }
    } catch (e) {
      print("error $e");
      return "";
    }
  }

  void _uploadFile(File fileToUpload) {
    _progress = 0;
    _uploadComplete = false;
    _errorMessage = '';

    gotipathStreamUploader
      ..endPoint = _endPoint
      ..clientID = _clientID
      ..libraryID = _libraryID
      ..apiKey = _apiKey
      ..videoID = _videoID
      ..file = fileToUpload
      ..onProgress = (double progress) {
        setState(() {
          _progress = progress.ceil();
        });
      }
      ..onError = (String message, int chunk, int attempts) {
        setState(() {
          _errorMessage =
              'UpChunk error 💥 🙀:\n - Message: $message\n - Chunk: $chunk\n - Attempts: $attempts';
        });
      }
      ..onSuccess = () {
        setState(() {
          _uploadComplete = true;
        });
      };

    gotipathStreamUploader.createUpload();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          children: [
            if (!_uploadComplete)
              Text(
                'Uploaded: $_progress%',
                style: TextStyle(
                  fontSize: 24,
                  fontWeight: FontWeight.normal,
                ),
              ),

            if (_uploadComplete)
              Text(
                'Upload complete! 👋',
                style: TextStyle(
                  fontSize: 24,
                  color: Colors.green,
                  fontWeight: FontWeight.bold,
                ),
              ),

            if (_errorMessage.isNotEmpty)
              Text(
                '$_errorMessage%',
                style: TextStyle(
                  fontSize: 24,
                  fontWeight: FontWeight.normal,
                  color: Colors.red,
                ),
              ),

            SizedBox(height: 30),
            InkWell(
              onTap: () {
                _uploadFile(File(fileToUpload));
              },
              child: Container(
                width: 200,
                height: 50,
                color: Colors.grey,
                child: Center(
                  child: Text(
                    'Video upload',
                    style: TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.normal,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ),
            SizedBox(height: 30),
            InkWell(
              onTap: () {
                gotipathStreamUploader.pause();
              },
              child: Container(
                width: 200,
                height: 50,
                color: Colors.blue,
                child: Center(
                  child: Text(
                    'Upload Pause',
                    style: TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.normal,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ),
            SizedBox(height: 30),
            InkWell(
              onTap: () {
                gotipathStreamUploader.resume();
              },
              child: Container(
                width: 200,
                height: 50,
                color: Colors.blue,
                child: Center(
                  child: Text(
                    'Upload Resume',
                    style: TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.normal,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ),

            SizedBox(height: 30),
            InkWell(
              onTap: () {
                gotipathStreamUploader.cancel();
              },
              child: Container(
                width: 200,
                height: 50,
                color: Colors.blue,
                child: Center(
                  child: Text(
                    'Upload Cancel',
                    style: TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.normal,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _getFile,
        tooltip: 'Get File',
        child: Icon(Icons.upload_file),
      ),
    );
  }
}

更多关于Flutter文件流上传插件gotipath_stream_uploader的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter文件流上传插件gotipath_stream_uploader的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


gotipath_stream_uploader 是一个用于在 Flutter 中实现文件流上传的插件。它允许你将文件分块上传,适用于大文件上传的场景。以下是使用 gotipath_stream_uploader 插件的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 gotipath_stream_uploader 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  gotipath_stream_uploader: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 导入插件

在你的 Dart 文件中导入 gotipath_stream_uploader 插件:

import 'package:gotipath_stream_uploader/gotipath_stream_uploader.dart';

3. 创建上传器实例

创建一个 StreamUploader 实例,并配置上传参数:

final uploader = StreamUploader(
  url: 'https://your-upload-endpoint.com/upload', // 上传的URL
  method: 'POST', // 请求方法,通常是 POST
  headers: {
    'Authorization': 'Bearer your_token', // 如果需要认证
  },
  chunkSize: 1024 * 1024, // 每个分块的大小,默认为 1MB
);

4. 开始上传

使用 upload 方法开始上传文件。你需要提供一个 File 对象和文件的 MIME 类型:

final file = File('path/to/your/file');
final mimeType = 'application/octet-stream'; // 文件的 MIME 类型

final response = await uploader.upload(file, mimeType);

if (response.statusCode == 200) {
  print('Upload successful!');
} else {
  print('Upload failed: ${response.statusCode}');
}

5. 处理上传进度

你可以监听上传进度,以便在 UI 中显示进度条或其他反馈:

uploader.onProgress.listen((progress) {
  print('Upload progress: ${progress.percentage}%');
});

6. 处理上传完成事件

你可以监听上传完成事件,以便在上传完成后执行一些操作:

uploader.onComplete.listen((response) {
  print('Upload completed with status code: ${response.statusCode}');
});

7. 错误处理

你可以监听错误事件,以便在上传过程中出现错误时进行处理:

uploader.onError.listen((error) {
  print('Upload error: $error');
});

8. 取消上传

如果需要取消上传,可以调用 cancel 方法:

uploader.cancel();

完整示例

以下是一个完整的示例,展示了如何使用 gotipath_stream_uploader 插件上传文件并显示上传进度:

import 'package:flutter/material.dart';
import 'package:gotipath_stream_uploader/gotipath_stream_uploader.dart';
import 'dart:io';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FileUploadScreen(),
    );
  }
}

class FileUploadScreen extends StatefulWidget {
  [@override](/user/override)
  _FileUploadScreenState createState() => _FileUploadScreenState();
}

class _FileUploadScreenState extends State<FileUploadScreen> {
  double _uploadProgress = 0.0;
  bool _isUploading = false;

  Future<void> _uploadFile() async {
    final file = File('path/to/your/file');
    if (!file.existsSync()) {
      print('File does not exist');
      return;
    }

    final uploader = StreamUploader(
      url: 'https://your-upload-endpoint.com/upload',
      method: 'POST',
      headers: {
        'Authorization': 'Bearer your_token',
      },
      chunkSize: 1024 * 1024,
    );

    setState(() {
      _isUploading = true;
    });

    uploader.onProgress.listen((progress) {
      setState(() {
        _uploadProgress = progress.percentage;
      });
    });

    final response = await uploader.upload(file, 'application/octet-stream');

    setState(() {
      _isUploading = false;
    });

    if (response.statusCode == 200) {
      print('Upload successful!');
    } else {
      print('Upload failed: ${response.statusCode}');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('File Upload'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (_isUploading)
              Column(
                children: [
                  CircularProgressIndicator(value: _uploadProgress / 100),
                  SizedBox(height: 10),
                  Text('Uploading: ${_uploadProgress.toStringAsFixed(2)}%'),
                ],
              ),
            ElevatedButton(
              onPressed: _isUploading ? null : _uploadFile,
              child: Text('Upload File'),
            ),
          ],
        ),
      ),
    );
  }
}
回到顶部