Conver Uint8List to file in flutterweb

Viewed 103

Hi I am having problem with uploading image inside flutter web and send it to server

i need to send image us a File type to server

before i ask, i will show u the code where i am struggling at

import 'dart:html';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import 'package:web_checkup/model/provider/reservation_provider.dart';

class CompanionImage extends StatefulWidget {
  const CompanionImage({Key? key}) : super(key: key);

  @override
  State<CompanionImage> createState() => _CompanionImageState();
}

class _CompanionImageState extends State<CompanionImage> {
  late ReservationPvd reservationPvd = context.read<ReservationPvd>();
  Uint8List webImage = Uint8List(8);
  bool uploaded = false;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        margin: EdgeInsets.only(bottom: 20),
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(100)),
        child: Stack(
          children: <Widget>[
            InkWell(
              highlightColor: Colors.transparent,
              splashColor: Colors.transparent,
              onTap: () => pickImage(),
              child: Container(
                height: 120,
                width: 120,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(100.0),
                ),
                child: uploaded ? Image.memory(webImage) : Image.asset('assets/images/paw.png'),
              ),
            ),
            Positioned(
              bottom: 0,
              right: 0,
              child: Container(
                width: 40,
                height: 40,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white,
                  border: Border.all(color: Color(0xFFe0e0e0)),
                ),
                padding: EdgeInsets.all(0),
                alignment: Alignment.center,
                child: IconButton(
                  icon: Icon(Icons.camera_alt, size: 20, color: Color(0xFFaaaaaa)),
                  onPressed: () => pickImage(),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  pickImage() async {
    final ImagePicker picker = ImagePicker();
    XFile? image = await picker.pickImage(source: ImageSource.gallery);
    var f = await image!.readAsBytes();
    setState(() {
      webImage = f;
      uploaded = true;
    });
    reservationPvd.updateInfo('imageFile', webImage);
  }
}

So the thing what I would like to do is making Xfile to File like the code below

File _file = image 

and other thing is too make Uint8List to file

File _file = webImage

like this

I have googled for a more that 4days but i wasn't able to find some examplse to make UintList to File neither XFile to File in Flutterweb

does anyone knows how to conver a File type in Flutterweb?

p.s i have already tried Universal_io or... some other packages and the Flutter version is 3.0.5

2 Answers

Why you nees parse it to File, just use XFile. And when upload to multipart just get bytes from XFile to upload.

        I have solved this issue by using https://pub.dev/packages/file_picker
          

    static  PlatformFile objFile = null;
              static  Uint8List uInt8List=null;
             static chooseFileUsingFilePicker() async {
                //-----pick file by file picker,    
                var result = await FilePicker.platform.pickFiles(
                withData: true,
                );
          
            
                if (result != null) {
                 objFile = result.files.single;
                debugPrint('result====>${result.toString()}'); 
uInt8List=result.files.first.bytes;
            // List<int> list = objFile.readStream.cast();
            return   uInt8List;
            }
            return null;
          }    

 static  Future<String> uploadSelectedFile() async {
    String endPoint='add ur endpoint';
    String param='add ur param';
    Stream<List<int>> stream;
  if(uInt8List!=null)  {
    stream= Stream.value(

        List<int>.from(uInt8List),
      );
    }
 
    //---Create http package multipart request object
    final request = http.MultipartRequest(
      POST,
      Uri.parse('your api goes here'),
    );
    // //-----add other fields if needed
    // request.fields["id"] = "abc";

    //-----add selected file with request
    request.files.add(new http.MultipartFile(
        param,uInt8List!=null?stream: objFile.readStream, objFile.size,
        filename: objFile.name));


    //-------Send request
    var resp =await callApi(PUT, endPoint, request, true);
    print(resp);

    if (resp != null) {
      print(jsonDecode(resp.body)['url']);

    return jsonDecode(resp.body)['url'] ?? '';
    }
    //-------Your response
  //  print(result);

    return null;
  }
Related