Flutter Desktop File Picker Result files. Bytes return null Error?

Viewed 745

I am building Flutter Desktop/Web Application. I use Flutter file_picker 4.02 pub its perfect working on flutter web after convert desktop app it have error in file selection return

file.byte return value null

FilePickerResult? result = await FilePicker.platform.pickFiles();

if (result != null) {
  PlatformFile file = result.files.first;

  print(file.name);
  **print(file.bytes);**
  print(file.size);
  print(file.extension);
  print(file.path);
 


} else {
  // User canceled the picker
}

I need to get selected results as byte ?

Flutter channels: Dev file_picker: ^4.0.2

1 Answers

I select only one file to upload from chrome. I use Stream.fromIterable to get map the bytes into a array. I create a MultipartFile with the filename,filesize and bytes array. Next, I use dio to post the FormData to an webapi. The [FromForm] is used to extract data from the formData posted by dio. IFormData binds to the multipart form data.

  FilePickerResult result = await FilePicker.platform.pickFiles(type:  FileType.any, allowMultiple: false);

  var fileName = result.files.first.name;
  var fileSize = fileBytes.length;

  FormData formData=FormData.fromMap({
    'id':id,
    'name':submitter,
    'file': MultipartFile(
  Stream.fromIterable(fileBytes.map((e) => [e])),
  fileSize,
  filename: fileName,
)}) ;

var url = Uri.parse(_BASE_URL + 'api/review/upload');
Dio dio=new Dio();
try
{
   String token = this.dataCache?.login?.jwtToken??"";
   Options options=new Options(
      contentType: Headers.formUrlEncodedContentType,
      headers:{
        Headers.contentLengthHeader: formFile.length,
      }
   );
   options.headers["Authorization"] = "Bearer " + token;
   
   dio.post(url.toString(),data:formFile, options:options);

Webapi

 public class FlutterFormData
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public IFormFile file { get; set; }
    }
    public async Task<IActionResult> UploadDocument([FromForm] FlutterFormData 
    formData, string name)
    {
        String retVal = "unprocessed";
        if (formData.file != null)
        {

            if (formData.file.Length > 0)
            {
                var filePath = Path.GetTempFileName();

                using (var stream = System.IO.File.Create(filePath))
                {
                    await formData.file.CopyToAsync(stream);
                    retVal = "Processed";
                }
            }
        }

        return Ok(retVal);
    }
Related