-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathreact-file-base64.js
76 lines (58 loc) · 1.52 KB
/
react-file-base64.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
/*! Copyright (c) 2016 Naufal Rabbani (http://github.com/BosNaufal)
* Licensed Under MIT (http://opensource.org/licenses/MIT)
*
* React File Base64 - Version@1.0.0
*
*/
import React from 'react';
export default class FileBase64 extends React.Component {
constructor(props) {
super(props);
this.state = {
files: [],
};
}
handleChange(e) {
// get the files
let files = e.target.files;
// Process each file
var allFiles = [];
for (var i = 0; i < files.length; i++) {
let file = files[i];
// Make new FileReader
let reader = new FileReader();
// Convert the file to base64 text
reader.readAsDataURL(file);
// on reader load somthing...
reader.onload = () => {
// Make a fileInfo Object
let fileInfo = {
name: file.name,
type: file.type,
size: Math.round(file.size / 1000) + ' kB',
base64: reader.result,
file: file,
};
// Push it to the state
allFiles.push(fileInfo);
// If all files have been proceed
if(allFiles.length == files.length){
// Apply Callback function
if(this.props.multiple) this.props.onDone(allFiles);
else this.props.onDone(allFiles[0]);
}
} // reader.onload
} // for
}
render() {
return (
<input
type="file"
onChange={ this.handleChange.bind(this) }
multiple={ this.props.multiple } />
);
}
}
FileBase64.defaultProps = {
multiple: false,
};