Flutter文件上传功能插件file_upload的使用

Flutter文件上传功能插件file_upload的使用

使用

请更改本地主机URL以匹配您的服务器URL。

import 'package:file_upload/file_upload.dart';

// 在此示例中我们使用了localhost URL,但您需要将其更改为您的服务器URL
String _url = 'http://10.0.2.2:5000';
FileUpload fileUpload = FileUpload();

Future<void> sendFiles() async {
  String url = '$_url/request1';
  /*
  uploadTwoFiles()
  参数:
    String url,
    String fileKey1,
    String filePath1,
    String fileType1,
    String fileKey2,
    String filePath2,
    String fileType2
  */
  var response1 = await fileUpload.uploadTwoFiles(
      url, 'video', path1!, 'mp4', 'image', path2!, 'jpg');
  print(response1);
}

Future<void> sendFile() async {
  /*uploadFile()
  参数:
      String url,
      String fileKey,
      String filePath,
      String fileType)
  */
  String url = '$_url/request2';
  // url, fileKey, filePath, fileType
  var response2 = await fileUpload.uploadFile(url, 'audio', path3!, 'wav');
  print(response2);
}

完整示例代码

以下是完整的示例代码:

import 'package:flutter/material.dart';
import 'package:file_upload/file_upload.dart';
import 'package:image_picker/image_picker.dart';
import 'package:file_picker/file_picker.dart';

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

class MyApp extends StatelessWidget {
  // 这个小部件是你的应用的根
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '文件上传示例',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: FileUploadExample(
        title: '文件上传示例',
      ),
    );
  }
}

class FileUploadExample extends StatefulWidget {
  FileUploadExample({Key? key, required this.title}) : super(key: key);

  final String title;

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

class _FileUploadExampleState extends State<FileUploadExample> {
  FileUpload fileUpload = FileUpload();
  Map<String, dynamic> response1 = {};
  List response2 = [];
  final ImagePicker _picker = ImagePicker();
  PickedFile? file1;
  PickedFile? file2;
  FileType? _pickingType = FileType.custom;
  String? path1;
  String? path2;
  String? path3;
  // 在此示例中我们使用了localhost URL,但您需要将其更改为您的服务器URL
  String _url = 'http://10.0.2.2:5000';

  Future getVideoFromGallery() async {
    file1 = await _picker.getVideo(source: ImageSource.gallery);
    setState(() {
      path1 = file1?.path;
      print(path1);
    });
  }

  Future getImageFromGallery() async {
    file2 = await _picker.getImage(source: ImageSource.gallery);
    setState(() {
      path2 = file2?.path;
      print(path2);
    });
  }

  void _pickFile3() async {
    FilePicker.platform.pickFiles(
      type: _pickingType!,
      onFileLoading: (FilePickerStatus status) => print(status),
      allowedExtensions: ['mp3', 'wav'],
    ).then((paths) async {
      path3 = paths?.files![0].path!.substring(1);
      print(path3);
    });
  }

  Future<void> sendFiles() async {
    String url = '$_url/request1';
    /*
    uploadTwoFiles()
    参数:
      String url,
      String fileKey1,
      String filePath1,
      String fileType1,
      String fileKey2,
      String filePath2,
      String fileType2
    */
    print(url);
    response1 = await fileUpload.uploadTwoFiles(
        url, 'video', path1!, 'mp4', 'image', path2!, 'jpg');
    print(response1);
  }

  Future<void> sendFile() async {
    String url = '$_url/request2';
    /*uploadFile()
  参数:
      String url,
      String fileKey,
      String filePath,
      String fileType)
  */
    response2 = await fileUpload.uploadFile(url, 'audio', path3!, 'wav');
    print(response2);
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          children: [
            ElevatedButton(
                onPressed: () {
                  getVideoFromGallery();
                },
                child: Text('选择文件1')),
            ElevatedButton(
                onPressed: () {
                  getImageFromGallery();
                },
                child: Text('选择文件2')),
            ElevatedButton(
                onPressed: () {
                  sendFiles();
                },
                child: Text('发送文件')),
            Text('$response1'),
            ElevatedButton(
                onPressed: () {
                  _pickFile3();
                },
                child: Text('选择文件3')),
            ElevatedButton(
                onPressed: () {
                  sendFile();
                },
                child: Text('发送文件')),
            Text('$response2'),
          ],
        ),
      ),
    );
  }
}

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

1 回复

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


当然,下面是一个使用 file_upload 插件在 Flutter 中实现文件上传功能的代码案例。需要注意的是,file_upload 并不是一个广泛认知的官方或流行插件,通常文件上传会结合 diohttp 插件来实现。不过,为了贴合你的要求,我假设这里提到的 file_upload 是一个假想的插件,并展示一个类似的实现过程。如果你实际使用的是另一个具体插件,请相应调整代码。

假设我们有一个假想的 file_upload 插件,其 API 可能类似于以下方式使用。这里我们将展示如何结合 Flutter 的文件选择和上传功能。

首先,确保在 pubspec.yaml 中添加必要的依赖项(假设有一个 file_upload 插件):

dependencies:
  flutter:
    sdk: flutter
  file_upload: ^x.y.z  # 替换为实际版本号
  path_provider: ^2.0.0  # 用于访问设备存储

然后,运行 flutter pub get 来获取依赖项。

接下来是代码实现:

import 'package:flutter/material.dart';
import 'package:file_upload/file_upload.dart';  // 假设的file_upload插件
import 'package:path_provider/path_provider.dart';
import 'dart:io';

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

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

class FileUploadScreen extends StatefulWidget {
  @override
  _FileUploadScreenState createState() => _FileUploadScreenState();
}

class _FileUploadScreenState extends State<FileUploadScreen> {
  File? _selectedFile;

  Future<void> _pickFile() async {
    final result = await FilePicker.platform.pickFiles();
    if (result != null) {
      final file = File(result.files.single.path!);
      setState(() {
        _selectedFile = file;
      });
    }
  }

  Future<void> _uploadFile() async {
    if (_selectedFile == null) return;

    // 假设 file_upload 插件有一个 uploadFile 方法
    final response = await FileUpload.uploadFile(
      url: 'https://example.com/upload',  // 替换为你的上传URL
      file: _selectedFile!,
      fieldName: 'file',
      headers: {
        'Authorization': 'Bearer YOUR_ACCESS_TOKEN',  // 如果需要认证
      },
    );

    // 处理响应
    print('Upload response: ${response.statusCode}, ${response.body}');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('File Upload Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextButton(
              onPressed: _pickFile,
              child: Text('Pick a file'),
            ),
            SizedBox(height: 16),
            if (_selectedFile != null)
              Text('Selected file: ${_selectedFile!.path}'),
            SizedBox(height: 16),
            TextButton(
              onPressed: _uploadFile,
              child: Text('Upload file'),
            ),
          ],
        ),
      ),
    );
  }
}

注意:上面的代码是基于一个假设的 file_upload 插件。在实际应用中,你可能需要使用 diohttp 插件来实现文件上传功能。例如,使用 dio 插件上传文件的代码可能如下所示:

import 'package:dio/dio.dart';
// ... 其他导入 ...

Future<void> _uploadFileWithDio() async {
  if (_selectedFile == null) return;

  final dio = Dio();
  FormData formData = FormData.fromMap({
    'file': await MultipartFile.fromFile(_selectedFile!.path, filename: basename(_selectedFile!.path)),
  });

  try {
    Response response = await dio.post('https://example.com/upload', data: formData);
    print('Upload response: ${response.statusCode}, ${response.data}');
  } catch (e) {
    print('Upload error: $e');
  }
}

在实际项目中,请根据你的具体需求和使用的插件调整代码。

回到顶部