How to upload file on server with nodejs

Viewed 294

I'm trying for several hours to upload files to my local server folder upload, but is being harder than expected, please help.

Below my front end to insert files form.hbs

<form action="/editcrew/" method="POST" encType="multipart/form-data" novalidate></form>
<input type="file" name="profile_image">
<button class="btn btn-primary" type="submit" style="margin:90px 0 0 0">Submit</button>
 

Here below my controller export.update located inside the file userController.js which successfully inserts the name of the file into MySql database.

exports.update = (req, res) => {
    
    const { first_name, last_name, profile_image } = req.body;

   

    connection.query('UPDATE user SET first_name=? ,last_name=?, profile_image=? ', [first_name, last_name, profile_image, req.params.id], (err, rows) => {
        if (!err) {
            connection.query('SELECT * FROM user WHERE id = ?', [req.params.id], (err, rows) => {
                //when done with the connection release it
                // connection.release();
                if (!err) {
                    res.render('edit-crew', { rows, alert: `${first_name} has been updated.` });
                } else {
                    console.log(err);
                }
                console.log('The data from user table:\n', rows);
            });
        } else {
            console.log(err);
        }
        console.log('The data from user table:\n', rows);
    });
};

Here below is the router for the post requests.

router.post('/editcrew/:id',userController.update);
For reference my app.js

const express = require("express");
const exphbs = require("express-handlebars");
const fileUpload = require('express-fileupload');

// const userContoller = require('./controllers/userController')
// to be removed when deployed in heroku

require("dotenv").config();
const cookieParser = require('cookie-parser');



// Parsing middleware
const app = express();

// default option
app.use(fileUpload());

//to load static file
app.use(express.static("public"));
app.use(express.static("upload"));
//Listen on port 5000
app.use(express.urlencoded({ extended: false })); //To parse URL-encoded bodies (as sent by HTML forms)

app.use(express.json()); //To parse the incoming requests with JSON bodies
app.use(cookieParser());

app.engine("hbs", exphbs({ extname: ".hbs" }));//Templating engine to change the extenion of file from .handlebar to .hbs
app.set("view engine", "hbs");


//link which tell to the server express.js to get the routeing from user.js
// const routes = require('./server/routes/user');
app.use("/", require('./routes/user'));
app.use('/auth', require('./routes/auth'));


const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on port ${port}`));

My goal is to have the controller update to not only insert name file on MySql database but also upload the file inside the local folder /upload

1 Answers

If you just want to upload file to the server and save the file . I would recommend you to use "multer" with expressjs . If you need extra features you can customize it . You can read the doc and start using it . here is the doc

Related