Found item by Category
Upload Image in MySQL database using Node js and React js
React

Upload Image in MySQL database using Node js and React js

React

<p>In this article, we will learn how to upload an image in React and Node using a library called<strong> Multer.</strong> So we will upload an image and insert a record in the MySQL database by using React frontend. <br />We will also learn how to view an image on the frontend.</p> <p><strong>Frontend</strong><br />We will create a basic client-side React app and then upload an image by creating an API in <strong>Node.js</strong> using Multer.</p> <ol> <li>&nbsp;We will first create a React app boilerplate as follows. <pre><code>npx install create-react-app frontend</code></pre> It will take some time to install. Once the installation is complete create a simple upload form in App.js.</li> <li>Create a simple form to upload an image in app.js <pre><code>return (<br />&lt;div className='App'&gt;<br />&lt;h1&gt;Upload to server&lt;/h1&gt;<br />{image.preview &amp;&amp; &lt;img src={image.preview} width='100' height='100' /&gt;}<br />&lt;hr&gt;&lt;/hr&gt;<br />&lt;form onSubmit={handleSubmit}&gt;<br />&lt;input type="file" name="imageFile" multiple onChange={onSelectFile} accept="image/png , image/jpeg, image/webp"/&gt;<br />&lt;/div&gt;<br />)</code></pre> </li> <li>Now we have to create 2 methods: <ol class="list" style="margin-top: 2px;"> <li style="font-weight: 400;" aria-level="1"><strong>handleSubmit()</strong><span style="font-weight: 400;"> : To submit the image data to the server.</span></li> <li style="font-weight: 400;" aria-level="1"><strong>onSelectFile()</strong><span style="font-weight: 400;"> :&nbsp; It will be triggered when the user selects the image file. It will display the image preview and store the image data in the state.</span>&nbsp;</li> </ol> </li> </ol> <pre><code> &nbsp; const App = () =&gt; {<br /> const [image, setImage] = useState({ preview: '', data: '' })<br /> const onSelectFile = (e) =&gt; {<br /> const img = {<br /> preview: URL.createObjectURL(e.target.files[0]),<br /> data: e.target.files[0],<br /> }<br /> setImage(img)<br /> };<br /> const handleSubmit =async (e) =&gt; {<br /> e.preventDefault();<br /> let formData = new FormData(); <br /> formData.append("imageFile", image.data);<br /> const response = await fetch('http://localhost:5000/imageUpload', {<br /> method: 'POST',<br /> body: formData,<br /> })<br /> if (response) setStatus(response.statusText)<br /> // }<br /> };<br /> }</code></pre> <p><span style="font-weight: 400;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Now go to the terminal and run </span><strong>npm start. </strong><span style="font-weight: 400;">You will see an image upload form.</span></p> <p><strong>Backend</strong><strong><br /></strong><span style="font-weight: 400;">Here we are using </span><strong>Multer</strong><span style="font-weight: 400;"> which will handle <code>"multipart/form-data"</code> sent from our form at frontend.</span></p> <ol start="4"> <li><span style="font-weight: 400;"> Create a file </span><strong>user.model.js</strong><span style="font-weight: 400;"><span style="font-weight: 400;"> and paste the following code into it. This will create tables in the MySQL database when the backend server is started.</span></span> <p><strong>&ndash;user.model.js</strong></p> <pre><code><span style="font-weight: 400;">module.exports = (sequelize, Sequelize) =&gt; {<br />const user = sequelize.define("user", {<br />imageFile: {<br /> &nbsp;type: Sequelize.TEXT('long'),</span> <span style="font-weight: 400;">}});return user;}; &gt;</span></code></pre> </li> <li><span style="font-weight: 400;">Create a file <code>user.routes.js</code> and paste the following code into it. In this code first, we are using </span><strong>Multer</strong><span style="font-weight: 400;"><span style="font-weight: 400;"> to upload the image in the uploads folder. We have imported the <code>user.controller</code> at the top which we will create in the next step. Then we created a route <code>&ldquo;/imageUpload&rdquo;</code> in which we are uploading an image using <code>upload.fields</code>. The field name must be the same as the input element in the frontend. Here the name is&nbsp; <code>&ldquo;</code><code>imageFile&rdquo;.</code><br /></span></span><strong style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;">&ndash;user.router.js</strong> <pre><code><span style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;"><span style="font-weight: 400;">const users = require("./user.Controller");<br />const multer = require("multer");<br />var storage = multer.diskStorage({<br />destination: function (req, file, cb) {<br />cb(null, "./uploads");<br />},<br />filename: function (req, file, cb) {<br />cb(null, file.originalname);<br />},<br />});<br />var upload = multer({ storage: storage });<br />module.exports = (app) =&gt; {<br />router.post("/imageUpload", upload.fields([<br />{ name: "imageFile" }<br />]), users.createUser);<br />}</span></span></code></pre> </li> <li> <p><span style="font-weight: 400;">Now create a file named user.Controller.js. Inside that, we are creating a method to create learning. Inside this function we will access the path of the image from the request which is: </span><code><strong>req?.files?.imageFile[0].path</strong></code></p> <strong>&ndash;user.controller.js</strong> <pre><code><span style="font-weight: 400;">const createLearn = async (req, res) =&gt; {<br />&nbsp; &nbsp;const saveLearnblogs = await LearnBlogs.create({<br />&nbsp; &nbsp; &nbsp;imageFile: req?.files?.imageFile[0].path, <br />&nbsp;})<br />}</span></code></pre> <pre><code>review: URL.createObjectURL(e.target.files[0]),<br /> data: e.target.files[0],<br />}<br />setImage(img)<br />};</code></pre> <pre><code>&lt;div className="formInput"&gt;<br />&lt;label&gt;Document&lt;/label&gt;<br />{/* &lt;img src={file} /&gt; */}<br />{/* &lt;input type="file" multiple={false} onChange={onSelectFile} name="imageFile" /&gt; */}<br />&lt;input type="file" name="imageFile" multiple onChange={onSelectFile} accept="image/png , image/jpeg, image/webp" style={{ display: "none" }} /&gt;<br />{/* &lt;img src={file.preview} /&gt; */}<br />{selectedImages &amp;&amp; selectedImages.map((image) =&gt; {<br />return (<br /> &lt;div key={image} className="image"&gt;<br /> &lt;img src={image} alt="upload" /&gt;<br /> &lt;/div&gt;<br />);<br />})}<br />&lt;/div&gt;</code></pre> <span style="font-weight: 400;">Now create a .env file where you will create a base URL of all the APIs. This URL will be used to fetch the image on the frontend view.</span></li> </ol> <p><strong>&nbsp; &nbsp; &nbsp; .env</strong></p> <pre><code>REACT_APP_BASE_API_URL=http://localhost:4249/</code></pre> <p><span style="font-weight: 400;">Now create a UserProfile.js functional component and paste the following code into it. Here we are passing the image file as props to the component which is then used to fetch the path of the image. </span></p> <p><strong>LearnCard.js</strong></p> <pre><code>function UserProfile({imageFile}) {<br />return (<br />&lt;div&gt;<br />&lt;div className="p-5 m-3"&gt;<br />&lt;img<br />src={`${REACT_APP_BASE_API_URL}${imageFile}`}<br />alt=""<br />width="400px"<br />/&gt;<br />&lt;/div&gt;<br />&lt;/div&gt;<br />);<br />}<br /><br /></code></pre> <p>Now you can call the UserProfile component inside <code>App.js</code> to display the uploaded image.</p> <p>&nbsp;</p>
Read More
Featured
Special title treatment

With supporting text below as a natural lead-in to additional content.

Go somewhere