Categories

Friday, July 26, 2024
#919814419350 therichposts@gmail.com
NodejsReactjs

Reactjs Nodejs Image Upload Show And Save Inside Folder Working Demo

Reactjs Nodejs Image Upload Show And Save Inside Folder Working Demo

Hello friends, welcome back to my blog. Today in this blog post, I am going to tell you, Reactjs Nodejs Image Upload Show And Save Inside Folder Working Demo.

Guys this demo is in React Twilio Chat Image Upload and Send

Reactjs image upload and save

For reactjs new comers, please check the below link:

Reactjs Basic Tutorials


Friends here is the code snippet for How to upload, preview and save image inside folder in react js? and please use this code snippet carefully to avoid the mistakes:

1. Firstly friends we need fresh reactjs setup and for that we need to run below commands into our terminal and also w should have latest node version installed on our system:

npx create-react-app reactimageupload

cd reactimageupload

npm start // run the project

2. Now we need to run below commands to get bootstrap(for good layout), react image uploading(for image upload ) and axios(to post image request to node)  modules into our react js app:

npm install bootstrap --save

npm install --save react-images-uploading

npm install axios --save

npm start

3. Finally friends we need to add below code into our src/App.js file to get final output on web browser:

import React from 'react';
import './App.css';

//bootstrap
import 'bootstrap/dist/css/bootstrap.min.css';

//For Image Save
import axios from 'axios';

//For Image Upload
import ImageUploading from "react-images-uploading";


class App extends React.Component {
  onChange = (imageList) => {
    // data for submit
    
    // Create an object of formData 
    const formData = new FormData(); 
     
    // Update the formData object 
    formData.append( 
      "myFile", 
      imageList[0].file, 
      imageList[0].file.name
    ); 
   
    // Details of the uploaded file 
    console.log(imageList[0].file); 
   
    // Request made to the backend api 
    // Send formData object to my nodejs for save in folder
    axios
      .post("http://localhost:5000/public/attachments", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
         
        },
      })
      .then((response) => {
    // handle the response
        console.log(response);
      })
      .catch((error) => {
        // handle errors
        console.log(error);
      });
  }; 
   

  render() {
   
    return (
     
      <div className="maincontainer">
        
        <h1 className="mr-5 ml-5 mt-5">TheRichPost</h1>
        <div className="container mb-5 mt-5">
        
        <ImageUploading
        onChange={this.onChange}
      >
        {({ imageList, onImageUpload }) => (
          // write your building UI
          <div className="imageuploader">

            <div className="mainBtns">
            <button className="btn btn-primary mr-1" onClick={onImageUpload}>Upload Image</button>
            
            </div>
            {imageList.map((image) => (
              <div className="imagecontainer" key={image.key}>
                <img src={image.dataURL} />
                
              </div>
            ))}
          </div>
        )}
      </ImageUploading>

       
            
      </div>

      
      </div>
      
)
};
}

export default App;

4. In the end friends we need to add below code into our src/App.css file to style the things:

.imagecontainer {
  float: left;
  width: 215px;
  height: auto;
  margin: 10px 0;
}
.imagecontainer img{width: 150px; margin:10px 0;}
.imageuploader{width: 800px; height: 400px; background-color:#cbeefc;padding: 10px;}
5. For moving image inside folder, friends here is my nodejs file App.js code, which I have used in reactjs:

Guys I have used nodejs to move image inside the nodeproject/public/attachments folder

Guys for node you have to add few modules like express, multer, cors etc

// Node/Express
const express = require('express');
const http = require('http');
const path = require('path');
const bodyParser = require('body-parser');
const multer = require('multer')


//attachments upload
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'public/attachments/')
  },
  filename: (req, file, cb) => {
    cb(null, file.originalname)
  },
})

const upload = multer({ storage: storage })

// Create Express webapp
const app = express();
const cors = require('cors');
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));

// Add body parser for Notify device registration
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.use(router);
//attachments upload
router.post('/public/attachments', upload.single('file'), function (req, res) {
  res.json({})
})

// Create http server and run it
const server = http.createServer(app);
const port = process.env.PORT || 5000;
server.listen(port, function() {
  console.log('Express server running on *:' + port);
});

module.exports = app;

Now we are done friends. If you have any kind of query or suggestion or any requirement then feel free to comment below.

Guys in my next post, I will tell you, how to upload and save multiple images in react js in folder?

Note: Friends, I just tell the basic setup and things, you can change the code according to your requirements. For better understanding must watch video above.
I will appreciate that if you will tell your views for this post.Nothing matters if your views will good or bad.

Jassa

Thanks

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 14, Angular 15, Angular 16, Angular 17, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.