Friday, July 29, 2022

[FIXED] how to upload file from frontend and post it in a local folder using fs and express

Issue

I think I should use fs but I am not pretty sure how

ejs:

<form action="/products" method="POST">
  <input type="file" name="image" id="image">
  <button class="submit">Submit</button>
</form>

app.js

app.post('/products', (req, res) => {
    console.log(req.body)
    console.log(req.body.image) //console logs a string
    fs.writeFile('./image.png', req.body.image, (err) => {
        if (err) throw err;

        console.log('saved!');
    });
    res.render('products', { title: 'bib' })
})
but it doesn't work since it's returning a string instead of a file and as I said I wanna save the file locally using fs


Solution

You can try using multer which is for uploading files in express.

const multer = require('multer')
const upload = multer({
    dest: 'path to where ever you want it to be saved locally in the server, eg ./images',
}) // the middleware

app.post('/products', upload.single('image'), (req, res) => {
    console.log(req.body)
    console.log(req.body.image) //console logs a string
    fs.writeFile('./image.png', req.body.image, (err) => {
        if (err) throw err;

        console.log('saved!');
    });
    res.render('products', { title: 'bib' })
})


Answered By - async
Answer Checked By - Cary Denson (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.