From 70a3d99ac1983118a89b15989a181bb6d34d33a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20Zen?= Date: Mon, 6 Jun 2016 10:40:11 -0300 Subject: [PATCH] Maps an image file DOMString to its toString function (So the File can be used straight into an image tag) --- src/components/Widgets/ImageControl.js | 44 ++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/src/components/Widgets/ImageControl.js b/src/components/Widgets/ImageControl.js index 6ea2de11..cc428562 100644 --- a/src/components/Widgets/ImageControl.js +++ b/src/components/Widgets/ImageControl.js @@ -3,11 +3,28 @@ import React from 'react'; export default class ImageControl extends React.Component { constructor(props) { super(props); + + this.state = { + currentImage: props.value + }; + + this.revokeCurrentImage = this.revokeCurrentImage.bind(this); 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); + this.renderImageName = this.renderImageName.bind(this); + } + + componentWillUnmount() { + this.revokeCurrentImage(); + } + + revokeCurrentImage() { + if (this.state.currentImage instanceof File) { + window.URL.revokeObjectURL(this.state.currentImage); + } } handleFileInputRef(el) { @@ -31,6 +48,7 @@ export default class ImageControl extends React.Component { handleChange(e) { e.stopPropagation(); e.preventDefault(); + this.revokeCurrentImage(); const fileList = e.dataTransfer ? e.dataTransfer.files : e.target.files; const files = [...fileList]; const imageType = /^image\//; @@ -42,18 +60,40 @@ export default class ImageControl extends React.Component { } }); + if (file) { + // Custom toString function on file, so it can be used on regular image fields + file.toString = function() { + return window.URL.createObjectURL(file); + }; + } + this.props.onChange(file); + this.setState({currentImage: file}); + } + + renderImageName() { + if (!this.state.currentImage) return null; + + if (this.state.currentImage instanceof File) { + return this.state.currentImage.name; + } else if (typeof this.state.currentImage === 'string') { + return this.state.currentImage; + } + + return null; } render() { + const imageName = this.renderImageName(); return (
- Click or drop image here. + + {imageName ? imageName : 'Click or drop imag here.'} +