如何从“文件选择器”flutter web中获取文件流值?

mrwjdhj3  于 2023-01-05  发布在  Flutter
关注(0)|答案(1)|浏览(188)

我需要从图库中选择一个图像,也有一个用于拖动图像的另一个字段。对于拖放字段,我使用flutter_dropzone。并使用getFileStream(event)数据上传数据到服务器。但file_picker: ^5.2.4是用于从图库中选择图像。因此,如何从这个包中获取文件流数据。我得到了字节,但这是行不通的,我需要文件流值
使用file_picker的代码

void chooseImage() async {
    pickedFile = await FilePicker.platform.pickFiles(
        type: FileType.custom,
      withReadStream: true,
      allowedExtensions: [
        'jpg','jpeg','png'
      ]
    );
    if (pickedFile != null) {
      try {
        base64   = pickedFile!.files.first.bytes;
        base64String.value=base64.toString();
        String mime = pickedFile!.files.first.extension.toString();
        getS3url("image/$mime" ,base64String.value,from: "cameraIcon");
//withReadStream
      //getFileStream(event);
      } catch (err) {
        print(err);
      }
    } else {

    }
  }
ffdz8vbo

ffdz8vbo1#

https://github.com/miguelpruivo/flutter_file_picker/wiki/FAQ复制

import 'package:file_picker/file_picker.dart';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
import 'package:mime/mime.dart';

void main() async {
  final result = await FilePicker.platform.pickFiles(
    type: FileType.custom,
    allowedExtensions: [
      'jpg',
      'png',
      'mp4',
      'webm',
    ],
    withData: false,
    withReadStream: true,
  );

  if (result == null || result.files.isEmpty) {
    throw Exception('No files picked or file picker was canceled');
  }

  final file = result.files.first;
  final filePath = file.path;
  final mimeType = filePath != null ? lookupMimeType(filePath) : null;
  final contentType = mimeType != null ? MediaType.parse(mimeType) : null;

  final fileReadStream = file.readStream;
  if (fileReadStream == null) {
    throw Exception('Cannot read file from null stream');
  }
  final stream = http.ByteStream(fileReadStream);

  final uri = Uri.https('siasky.net', '/skynet/skyfile');
  final request = http.MultipartRequest('POST', uri);
  final multipartFile = http.MultipartFile(
    'file',
    stream,
    file.size,
    filename: file.name,
    contentType: contentType,
  );
  request.files.add(multipartFile);

  final httpClient = http.Client();
  final response = await httpClient.send(request);

  if (response.statusCode != 200) {
    throw Exception('HTTP ${response.statusCode}');
  }

  final body = await response.stream.transform(utf8.decoder).join();

  print(body);
}

相关问题