Search code examples
javascriptnode.jsexpressmultipartform-dataformidable

Display images from multipart/form-data parsers without saving


In this question, images uploaded through multipart/form-data parsers are saved in a temp folder const tempPath = req.file.path. Then they are copied to a specified directory const targetPath = path.join(__dirname, "./uploads/image.png"); Those images then can be displayed like <img src="/uploads/image.png" />

I understand that browser cannot display an image in system's temp folder. Is there another way to display images without copying them like above? Can I convert req.file to be displayed in <img />?


Solution

  • You can display the image on the client side without send the image to the server side by listening to the onChange event of the input with the file type. This is how I do with ReactJS (Demo on CodeSandbox)

    class App extends React.Component {
        state = { imageSrc: '' };
    
        onImageChange = (event) => {
            if(event.target.files.length !== 0) {
                const reader = new FileReader();
    
                reader.onload = (e) => {
                this.setState({ imageSrc: e.target.result });
            }
    
            reader.readAsDataURL(event.target.files[0]);
        }
     }
    
      render() {
            return (
                <div className="App">
                    <input type="file" accept="image/*" onChange={this.onImageChange} />
                    {this.state.imageSrc ? <img src={this.state.imageSrc} /> : null}
                </div>
            );
       }
    }
    

    Hope it helps. Let me know if I misuderstand your question