This repository has been archived by the owner on Oct 8, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
/
ReactFileReader.js
110 lines (92 loc) · 2.52 KB
/
ReactFileReader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import React from 'react';
import PropTypes from 'prop-types';
export default class ReactFileReader extends React.Component {
fileInput = null;
setFileInput = element => {
this.fileInput = element;
}
clickInput = () => {
const element = this.fileInput;
element.value = '';
element.click();
}
handleFiles = (event) => {
if(this.props.base64) {
this.convertFilesToBase64(event.target.files);
} else {
this.props.handleFiles(event.target.files);
}
}
convertFilesToBase64 = (files) => {
let ef = files;
if (this.props.multipleFiles) {
let files = { base64: [], fileList: ef };
for (var i = 0, len = ef.length; i < len; i++) {
let reader = new FileReader();
let f = ef[i];
reader.onloadend = e => {
files.base64.push(reader.result);
if (files.base64.length === ef.length) {
this.props.handleFiles(files);
}
}
reader.readAsDataURL(f);
}
} else {
let files = { base64: '', fileList: ef };
let f = ef[0];
let reader = new FileReader();
reader.onloadend = e => {
files.base64 = reader.result;
this.props.handleFiles(files);
}
reader.readAsDataURL(f);
}
}
render() {
var hideInput = {
width: '0px',
opacity: '0',
position: 'fixed',
}
const optionalAttributes = {};
if (this.props.elementId) {
optionalAttributes.id = this.props.elementId;
}
return(
<div className='react-file-reader'>
<input type='file'
onChange={this.handleFiles}
accept={Array.isArray(this.props.fileTypes) ? this.props.fileTypes.join(',') : this.props.fileTypes}
className='react-file-reader-input'
ref={this.setFileInput}
multiple={this.props.multipleFiles}
style={hideInput}
disabled={this.props.disabled}
{...optionalAttributes}
/>
<div className='react-file-reader-button' onClick={this.clickInput}>
{this.props.children}
</div>
</div>
)
}
}
ReactFileReader.defaultProps = {
fileTypes: 'image/*',
multipleFiles: false,
base64: false,
disabled: false,
};
ReactFileReader.propTypes = {
multipleFiles: PropTypes.bool,
handleFiles: PropTypes.func.isRequired,
fileTypes: PropTypes.oneOfType([
PropTypes.string,
PropTypes.array,
]),
base64: PropTypes.bool,
children: PropTypes.element.isRequired,
disabled: PropTypes.bool,
elementId: PropTypes.string,
};