2

How do I show a file preview for PFD/docx/xls/jpg files using React.js or web?

This question has been asked before but no one has answered, so I'm trying to get more attention: React File Preview (FIREBASE)

File preview for web

Someone please answer.

etayluz
  • 14,907
  • 20
  • 95
  • 141
  • This one liner worked great: https://stackoverflow.com/questions/27957766/how-do-i-render-a-word-document-doc-docx-in-the-browser-using-javascript – etayluz Jun 19 '18 at 16:04

1 Answers1

0

You can load a preview of any image (not PDF/Docx though) by using the FileReader class.

This class will load a preview and execute a callback when its done, where you can set the state of your component.

Working example :

class PicturePreview extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            preview: ''
        }
    }

    fileUploaded = ev => {
        const reader = new FileReader()
        reader.readAsDataURL(ev.target.files[0])
        reader.onloadend = ev => {
            this.setState({ preview: reader.result })
        }
    }

    render() {
        const { preview } = this.state

        return (
            <div>
                <input type='file' onChange={this.fileUploaded} />
                {preview && <img className='previewFile' src={preview} alt='preview' />}
            </div >
        )
    }
}

ReactDOM.render(<PicturePreview/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.2/umd/react-dom.production.min.js"></script>
<div id='root'>
Treycos
  • 7,192
  • 3
  • 22
  • 40
  • This solution will only work for image files. Not for PFD/docx/xls – Yusufali2205 Oct 18 '19 at 18:43
  • 1
    Yes this is indicated in the first sentence of my answer – Treycos Oct 18 '19 at 22:28
  • @Treycos then no need of this libraries and extra work, you can just create object url using URL.createObjectURL() method and provide it as a src to image. The question is about to preview all type of files not only image files. – Vaibhav Gidde Nov 12 '21 at 06:34