Skip to content

Instantly share code, notes, and snippets.

@rijdz
Last active November 28, 2018 09:16
Show Gist options
  • Save rijdz/187301fb201e96029ab26df0d8088bd8 to your computer and use it in GitHub Desktop.
Save rijdz/187301fb201e96029ab26df0d8088bd8 to your computer and use it in GitHub Desktop.
react-upload-download-csv
masterId,description,status
10001,Template #1,split
10002,Template #2,integrated
class UploadFileModal extends React.Component {
constructor(props) {
super(props);
this.state = {
file:{},
masterId: '',
description: ''
};
this.onFileSelected = this.onFileSelected.bind(this);
}
onDownloadCsv(){
const arr = [];
arr.push(['masterId','description','status']);
arr.push(['10001','Template #1','split']);
arr.push(['10002','Template #2','integrated']);
console.log('this is array');
console.log(arr);
let dataString = '';
let csvContent = 'data:text/csv;charset=utf-8,';
arr.forEach((d, index) => {
dataString = d.join(',');
csvContent += index < (arr.length - 1) ? dataString + '\n' : dataString;
});
const encodedUri = encodeURI(csvContent);
const link = document.createElement('a');
link.setAttribute('href', encodedUri);
link.setAttribute('download', 'master_template.csv');
link.click();
}
onFileSelected(event){
console.log('file handler');
console.log(event.target.files[0]);
this.setState({file: event.target.files[0]});
}
onUploadCsv(){
console.log('inside upload csv');
console.log(this.state.file);
const file = this.state.file;
console.log('this is the result');
Papa.parse(file, {
complete: (results) => {
if (!results.error) {
console.log('Finished: ', results.data);
}
}
});
}
render() {
const formElements = <fieldset>
{alert}
<input
type="file"
onChange={this.onFileSelected}
value={this.state.file}
accept='.csv'/>
<br />
<ControlGroup hideLabel={true} hideHelp={true}>
<Button
type="submit"
inputClasses={{ 'btn-primary': true }}
disabled={this.props.loading}
onClick={this.onUploadCsv.bind(this)}>
Upload File
<Spinner space="left" show={this.props.loading} />
</Button>
<Button
inputClasses={{ 'btn-success': true, 'pull-right': true }}
disabled={this.props.loading}
onClick={this.onDownloadCsv.bind(this)}>
Download Template
<Spinner space="left" show={this.props.loading} />
</Button>
</ControlGroup>
</fieldset>;
return (
<Modal
header="Upload File"
show={this.props.show}
onClose={Actions.hideUploadFile}>
{formElements}
</Modal>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment