-2

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
Baraa Baba
  • 63
  • 1
  • 5

2 Answers2

0

See The Form Element on MDN:

enctype

If the value of the method attribute is post, enctype is the MIME type of the form submission. Possible values:

  • application/x-www-form-urlencoded: The default value.
  • multipart/form-data: Use this if the form contains elements with type=file.

You have not set the <form enctype="multipart/form-data"> so the browser will not upload the data.


Your server-side code is missing the part where you add the body parsing middleware, but if it is supporting the form you have then it is for URL Encoded Form Data and not for Multipart Form Data.

You need a body parser that can handle the data format you are using.

Express is packaged with body-parser which doesn't support multipart form bodies but suggests a number of options.

This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:

  • busboy and connect-busboy
  • multiparty and connect-multiparty
  • formidable
  • multer

Multer is probably the most popular of those.

You'll need something like:

app.post('/products', upload.single('image'), (req, res) => {

… where upload is provided by Multer and image is the name of the file input. You can then access the image via req.file.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

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' })
})
async
  • 162
  • 8