Custom Upload Button w/ File Preview

const styleHidden = { display: 'none' } const CustomUpload = React.createClass({ getInitialState() { return { previewURL: null, file: null } }, handleSubmit(e) { // Handle file submission here e.preventDefault(); console.log('Submitting...nothing!'); }, handleButtonClick( e ) { e.preventDefault(); let hiddenInput = this.refs.hiddenInput; hiddenInput.click(); }, handleFileChange( {target} ) { let fileDisplay = this.refs.fileDisplay; let fileInfo = target.files[0]; let fileName = target.files[0].name; let fileSize = Math.round(fileInfo.size / 1024); let reader = new FileReader(); fileDisplay.innerText = `${fileName} (${fileSize} KB)`; console.log(`File uploaded: ${fileInfo.name}`); console.log(fileInfo); reader.onloadend = () => { let preview = reader.result; this.setState({ previewURL: preview, file: fileInfo }); } reader.readAsDataURL(fileInfo); }, removeFile(e) { e.preventDefault(); let hiddenInput = this.refs.hiddenInput; let fileDisplay = this.refs.fileDisplay; if(hiddenInput.value) { try { // For modern browsers console.log(`Removing ${hiddenInput.value} path from file input...`); hiddenInput.value = ""; fileDisplay.innerText = "Please select file"; console.log('File Removed'); console.log(hiddenInput.files); this.setState({ previewURL: null, file: null }); } catch(err) { // For IE 10- let wrap = document.createElement('form'), parentNode = hiddenInput.parentNode, ref = hiddenInput.nextSibling; wrap.appendChild(hiddenInput); wrap.reset(); parentNode.insertBefore(hiddenInput, ref); fileDisplay.innerText = "No file selected"; console.log('File Removed'); console.log(hiddenInput.files); this.setState({ previewURL: null, file: null }); } } }, validateFile( {target} ) { // validate that file 2 make it gud }, render: function() { let bgStyle = { backgroundImage: `url(${this.state.previewURL})`, display: 'inline-block', width: '50px', height: '50px', overflow: 'hidden', backgroundSize: '100%', backgroundRepeat: 'no-repeat' }; return ( <form onSubmit={(e) => this.handleSubmit(e)} id="fileUpload" > <h2>Upload your file home slice!</h2> <div className="custom-upload"> <div className="filePreview"> <span className="preview" style={bgStyle}></span> <p ref="fileDisplay">No file selected</p> </div> <button onClick={(e) => this.handleButtonClick(e)} >Select File</button> <button onClick={(e) => this.removeFile(e)}>Remove File</button> </div> <input type="file" onChange={(e) => this.handleFileChange(e)} ref="hiddenInput" style={styleHidden} /> <input type="submit" value="Submit" onClick={(e) => this.handleSubmit(e)} /> </form> ); } }); ReactDOM.render(<CustomUpload />, document.getElementById('container'));
Custom upload component built using React. Includes a file preview with file size.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.