Support for image preview & drag and drop

This commit is contained in:
Cássio Zen 2016-06-05 23:22:12 -03:00
parent 75231bee83
commit ade51b27fc
2 changed files with 65 additions and 4 deletions

View File

@ -4,13 +4,70 @@ export default class ImageControl extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleFileInputRef = this.handleFileInputRef.bind(this);
this.handleClick = this.handleClick.bind(this);
this.handleDragEnter = this.handleDragEnter.bind(this);
this.handleDragOver = this.handleDragOver.bind(this);
}
handleFileInputRef(el) {
this._fileInput = el;
}
handleClick(e) {
this._fileInput.click();
}
handleDragEnter(e) {
e.stopPropagation();
e.preventDefault();
}
handleDragOver(e) {
e.stopPropagation();
e.preventDefault();
}
handleChange(e) {
this.props.onChange(e.target.value);
e.stopPropagation();
e.preventDefault();
const fileList = e.dataTransfer ? e.dataTransfer.files : e.target.files;
const files = [...fileList];
const imageType = /^image\//;
// Iterate to list of files and return the first image on the list
const file = files.find((currentFile) => {
if (imageType.test(currentFile.type)) {
return currentFile;
}
});
this.props.onChange(file);
}
render() {
return <input type="file" onChange={this.handleChange}/>;
return (
<div
onClick={this.handleClick}
onDragEnter={this.handleDragEnter}
onDragOver={this.handleDragOver}
onDrop={this.handleChange}
>
Click or drop image here.
<input
type="file"
accept="image/*"
onChange={this.handleChange}
style={styles.input}
ref={this.handleFileInputRef}
/>
</div>
);
}
}
const styles = {
input: {
display: 'none'
}
};

View File

@ -3,11 +3,15 @@ import React from 'react';
export default class ImagePreview extends React.Component {
constructor(props) {
super(props);
this.handleImageLoaded = this.handleImageLoaded.bind(this);
}
handleImageLoaded() {
window.URL.revokeObjectURL(this.props);
}
render() {
const { value } = this.props;
return value ? <img src={value}/> : null;
return value ? <img src={window.URL.createObjectURL(value)} onLoad={this.handleImageLoaded} /> : null;
}
}