Home > Blockchain >  How to get file stream value from "file_picker" flutter web?
How to get file stream value from "file_picker" flutter web?

Time:01-06

I need to pick an image from gallery and also have an another field for drag image. For drag and drop field I used flutter_dropzone. and used getFileStream(event) data to upload data into server.But file_picker: ^5.2.4 is used to pick image from gallery.So how to get filestream data from this package. I got bytes but that is not working I needed filestream value

Code using 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 {

    }
  }

CodePudding user response:

Copied from 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);
}
  • Related