This repository has been archived by the owner on Jun 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 155
/
index.js
302 lines (271 loc) · 7.99 KB
/
index.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import React from 'react';
import PropTypes from 'prop-types';
import './index.css';
import FlipMove from 'react-flip-move';
import UploadIcon from './UploadIcon.svg';
const styles = {
display: "flex",
alignItems: "center",
justifyContent: "center",
flexWrap: "wrap",
width: "100%"
};
const ERROR = {
NOT_SUPPORTED_EXTENSION: 'NOT_SUPPORTED_EXTENSION',
FILESIZE_TOO_LARGE: 'FILESIZE_TOO_LARGE'
}
class ReactImageUploadComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
pictures: [...props.defaultImages],
files: [],
fileErrors: []
};
this.inputElement = '';
this.onDropFile = this.onDropFile.bind(this);
this.onUploadClick = this.onUploadClick.bind(this);
this.triggerFileUpload = this.triggerFileUpload.bind(this);
}
componentDidUpdate(prevProps, prevState, snapshot){
if(prevState.files !== this.state.files){
this.props.onChange(this.state.files, this.state.pictures);
}
}
/*
Load image at the beggining if defaultImage prop exists
*/
componentWillReceiveProps(nextProps){
if(nextProps.defaultImages !== this.props.defaultImages){
this.setState({pictures: nextProps.defaultImages});
}
}
/*
Check file extension (onDropFile)
*/
hasExtension(fileName) {
const pattern = '(' + this.props.imgExtension.join('|').replace(/\./g, '\\.') + ')$';
return new RegExp(pattern, 'i').test(fileName);
}
/*
Handle file validation
*/
onDropFile(e) {
const files = e.target.files;
const allFilePromises = [];
const fileErrors = [];
// Iterate over all uploaded files
for (let i = 0; i < files.length; i++) {
let file = files[i];
let fileError = {
name: file.name,
};
// Check for file extension
if (!this.hasExtension(file.name)) {
fileError = Object.assign(fileError, {
type: ERROR.NOT_SUPPORTED_EXTENSION
});
fileErrors.push(fileError);
continue;
}
// Check for file size
if(file.size > this.props.maxFileSize) {
fileError = Object.assign(fileError, {
type: ERROR.FILESIZE_TOO_LARGE
});
fileErrors.push(fileError);
continue;
}
allFilePromises.push(this.readFile(file));
}
this.setState({
fileErrors
});
const {singleImage} = this.props;
Promise.all(allFilePromises).then(newFilesData => {
const dataURLs = singleImage?[]:this.state.pictures.slice();
const files = singleImage?[]:this.state.files.slice();
newFilesData.forEach(newFileData => {
dataURLs.push(newFileData.dataURL);
files.push(newFileData.file);
});
this.setState({pictures: dataURLs, files: files});
});
}
onUploadClick(e) {
// Fixes https://github.com/JakeHartnell/react-images-upload/issues/55
e.target.value = null;
}
/*
Read a file and return a promise that when resolved gives the file itself and the data URL
*/
readFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
// Read the image via FileReader API and save image result in state.
reader.onload = function (e) {
// Add the file name to the data URL
let dataURL = e.target.result;
dataURL = dataURL.replace(";base64", `;name=${file.name};base64`);
resolve({file, dataURL});
};
reader.readAsDataURL(file);
});
}
/*
Remove the image from state
*/
removeImage(picture) {
const removeIndex = this.state.pictures.findIndex(e => e === picture);
const filteredPictures = this.state.pictures.filter((e, index) => index !== removeIndex);
const filteredFiles = this.state.files.filter((e, index) => index !== removeIndex);
this.setState({pictures: filteredPictures, files: filteredFiles}, () => {
this.props.onChange(this.state.files, this.state.pictures);
});
}
/*
Check if any errors && render
*/
renderErrors() {
const { fileErrors } = this.state;
return fileErrors.map((fileError, index) => {
return (
<div className={'errorMessage ' + this.props.errorClass} key={index} style={this.props.errorStyle}>
* {fileError.name} {fileError.type === ERROR.FILESIZE_TOO_LARGE ? this.props.fileSizeError: this.props.fileTypeError}
</div>
);
});
}
/*
Render the upload icon
*/
renderIcon() {
if (this.props.withIcon) {
return <img src={UploadIcon} className="uploadIcon" alt="Upload Icon" />;
}
}
/*
Render label
*/
renderLabel() {
if (this.props.withLabel) {
return <p className={this.props.labelClass} style={this.props.labelStyles}>{this.props.label}</p>
}
}
/*
Render preview images
*/
renderPreview() {
return (
<div className="uploadPicturesWrapper">
<FlipMove enterAnimation="fade" leaveAnimation="fade" style={styles}>
{this.renderPreviewPictures()}
</FlipMove>
</div>
);
}
renderPreviewPictures() {
return this.state.pictures.map((picture, index) => {
return (
<div key={index} className="uploadPictureContainer">
<div className="deleteImage" onClick={() => this.removeImage(picture)}>X</div>
<img src={picture} className="uploadPicture" alt="preview"/>
</div>
);
});
}
/*
On button click, trigger input file to open
*/
triggerFileUpload() {
this.inputElement.click();
}
clearPictures() {
this.setState({pictures: []})
}
render() {
return (
<div className={"fileUploader " + this.props.className} style={this.props.style}>
<div className="fileContainer" style={this.props.fileContainerStyle}>
{this.renderIcon()}
{this.renderLabel()}
<div className="errorsContainer">
{this.renderErrors()}
</div>
<button
type={this.props.buttonType}
className={"chooseFileButton " + this.props.buttonClassName}
style={this.props.buttonStyles}
onClick={this.triggerFileUpload}
>
{this.props.buttonText}
</button>
<input
type="file"
ref={input => this.inputElement = input}
name={this.props.name}
multiple={!this.props.singleImage}
onChange={this.onDropFile}
onClick={this.onUploadClick}
accept={this.props.accept}
/>
{ this.props.withPreview ? this.renderPreview() : null }
</div>
</div>
)
}
}
ReactImageUploadComponent.defaultProps = {
className: '',
fileContainerStyle: {},
buttonClassName: "",
buttonStyles: {},
withPreview: false,
accept: "image/*",
name: "",
withIcon: true,
buttonText: "Choose images",
buttonType: "button",
withLabel: true,
label: "Max file size: 5mb, accepted: jpg|gif|png",
labelStyles: {},
labelClass: "",
imgExtension: ['.jpg', '.jpeg', '.gif', '.png'],
maxFileSize: 5242880,
fileSizeError: " file size is too big",
fileTypeError: " is not a supported file extension",
errorClass: "",
style: {},
errorStyle: {},
singleImage: false,
onChange: () => {},
defaultImages: []
};
ReactImageUploadComponent.propTypes = {
style: PropTypes.object,
fileContainerStyle: PropTypes.object,
className: PropTypes.string,
onChange: PropTypes.func,
onDelete: PropTypes.func,
buttonClassName: PropTypes.string,
buttonStyles: PropTypes.object,
buttonType: PropTypes.string,
withPreview: PropTypes.bool,
accept: PropTypes.string,
name: PropTypes.string,
withIcon: PropTypes.bool,
buttonText: PropTypes.string,
withLabel: PropTypes.bool,
label: PropTypes.string,
labelStyles: PropTypes.object,
labelClass: PropTypes.string,
imgExtension: PropTypes.array,
maxFileSize: PropTypes.number,
fileSizeError: PropTypes.string,
fileTypeError: PropTypes.string,
errorClass: PropTypes.string,
errorStyle: PropTypes.object,
singleImage: PropTypes.bool,
defaultImages: PropTypes.array
};
export default ReactImageUploadComponent;