Convert CSV to JSON client side with React DropZon

2019-05-11 07:40发布

Is this possible to do?

From React dropzone, i receive a File object with a File.preview property whose value is a blob:url. i.e. File {preview: "blob:http://localhost:8080/52b6bad4-58f4-4ths-a2f5-4ee258ba864a"

Is there a way to convert this to json on the client? The file isnt need to be stored in a database (the convert JSON will be). I've attempted to use csvtojson but it's unable to use the file system as it uses node to power it. Ideally would like to convert this in the client if possible, once user has uploaded it. Any suggestions welcomed.

        <Dropzone
            name={field.name}
            onDrop={(acceptedFiles, rejectedFiles) => {
                acceptedFiles.forEach(file => {
                    console.log(file)
                    let tempFile = file.preview
                    csv()
                        .fromSteam(tempFile) // this errors with fs.exists not a function as its not running serverside

                        .on('end_parsed',(jsonArrObj)=>{
                            console.log(jsonArrObj)
                        })
                })
            }}
        >

2条回答
我想做一个坏孩纸
2楼-- · 2019-05-11 07:56

Yes, its possible with FileReader and csv:

import csv from 'csv';

// ...

const onDrop = onDrop = (e) => {
    const reader = new FileReader();
    reader.onload = () => {
        csv.parse(reader.result, (err, data) => {
            console.log(data);
        });
    };

    reader.readAsBinaryString(e[0]);
}

// ...

<Dropzone name={field.name} onDrop={onDrop} />

FileReader API: https://developer.mozilla.org/en/docs/Web/API/FileReader
csv package: https://www.npmjs.com/package/csv

查看更多
Deceive 欺骗
3楼-- · 2019-05-11 08:06

Joe's helpful response prompted me to collate my own resources for anyone else here: Yes, FileReader was the one!

Credit goes to these to guys here and here for converting JSON to CSV on uploading file to use with redux-form and redux-dropzone-form

EDIT: Github repo coming soon for completeness

查看更多
登录 后发表回答