2

I would like to upload csv file in Flutter. I am using FileUploadInputElement for file browsing. The problem I issue is how to convert the data to csv format.

This is currently the code I am using:

class _GenesTableTabState extends State<GenesTableTab> {
  Uint8List uploadedCsv;
  String option1Text;

  _startFilePicker() async {
    InputElement uploadInput = FileUploadInputElement();
    uploadInput.click();

    uploadInput.onChange.listen((e) {
      // read file content as dataURL
      final files = uploadInput.files;
      if (files.length == 1) {
        final file = files[0];
        FileReader reader = FileReader();

        reader.onLoadEnd.listen((e) {
          setState(() {
            uploadedCsv = Base64Decoder()
                .convert(reader.result.toString().split(",").last);
          });
        });

        reader.onError.listen((fileEvent) {
          setState(() {
            option1Text = "Some Error occured while reading the file";
          });
        });

        reader.readAsDataUrl(file);
      }
    });
  }

I don't know how to handle uploadedCsv field after the decoding.

2 Answers 2

3

You can copy paste run full code below
You can check uploadedCsv and do convert

uploadedCsv == null
            ? Container()
            : Text(String.fromCharCodes(uploadedCsv)),
uploadedCsv == null
            ? Container()
            : Text(utf8.decode(uploadedCsv)),

working demo

enter image description here

enter image description here

full code

import 'dart:convert';
import 'dart:html';
import 'dart:typed_data';

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: GenesTableTab(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

  @override
  _GenesTableTabState createState() => _GenesTableTabState();
}

class _GenesTableTabState extends State<GenesTableTab> {
  Uint8List uploadedCsv;
  String option1Text;

  _startFilePicker() async {
    InputElement uploadInput = FileUploadInputElement();
    uploadInput.click();

    uploadInput.onChange.listen((e) {
      // read file content as dataURL
      final files = uploadInput.files;
      if (files.length == 1) {
        final file = files[0];
        FileReader reader = FileReader();

        reader.onLoadEnd.listen((e) {
          setState(() {
            uploadedCsv = Base64Decoder()
                .convert(reader.result.toString().split(",").last);
            print(utf8.decode(uploadedCsv));
          });
        });

        reader.onError.listen((fileEvent) {
          setState(() {
            option1Text = "Some Error occured while reading the file";
          });
        });

        reader.readAsDataUrl(file);
      }
    });
  }

  int _counter = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            uploadedCsv == null
                ? Container()
                : Text(String.fromCharCodes(uploadedCsv)),
            uploadedCsv == null
                ? Container()
                : Text(utf8.decode(uploadedCsv)),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _startFilePicker,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Here's how I handled it

Uint8List uploadedCsv = new Uint8List(0);
String option1Text = "";

 if (kIsWeb)
{
  print('registering as web file picker');
    startWebFilePicker();
}

//....


 startWebFilePicker() async {
    html.FileUploadInputElement uploadInput = html.FileUploadInputElement();
    uploadInput.click();

          uploadInput.onChange.listen((e) {
        // read file content as dataURL
        final files = uploadInput.files;
        if (files!.length == 1) {
          final file = files[0];
          html.FileReader reader = html.FileReader();

          reader.onLoadEnd.listen((e) {
            setState(() async {
              uploadedCsv = Base64Decoder()
                  .convert(reader.result.toString().split(",").last);

              final fields = CsvToListConverter().convert(utf8.decode(uploadedCsv));
                print(fields);
                setState(() {
                  itemData=fields;
                });

              print('uploadedCSV is now ' + utf8.decode(uploadedCsv)); // utf8.decode returns the UInt8List to readable csv
            });
          });

          reader.onError.listen((fileEvent) {
            setState(() {
              option1Text = "Some Error occured while reading the file";
            });
          });

          reader.readAsDataUrl(file);

        }
      });

  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.