I was working on a small project on backend using nodeJS. I want to upload image to backend. I'm using nodeJS for backend and using packages like express, body-parser & multer.
I build a simple project to upload image, for now I just want that image is uploaded & stored in "public" folder that is in same level as server.js
server.js file
const express = require('express')
const multer= require('multer')
const path= require('path')
const bodyParser= require('body-parser')
const app = express()
const storage= multer.diskStorage({
destination: (req,file,cb)=>{
cb(null,"public")
},
filename: (req,file,cb)=>{
console.log(file);
cb(null, Date.now()+'-'+file.originalname);
}
})
app.use( bodyParser.urlencoded({ extended: true }) );
const uploads= multer({storage:storage})
app.post('/upload', uploads.single('image'), (req, res){
res.sendFile(req.file) // just send back json data of file that is uploaded
})
app.get('/',(req,res) =>{
res.sendFile(path.resolve(__dirname,'./index.html'))
});
app.listen(8000, ()=> console.log('Server Running at port: 8000'))
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit">
</form>
</body>
</html>
I've also created a 'public' folder for storing files. Tried all possible ways available, read official document, watched videos but I'm unable to get it right. When I'm sending a post request I'm able to get data as req.body but I'm not getting req.file, I want to take the file that is uploaded in post request and save it in public folder.
try setting up destination
path with path
module, like on the GET route below.
try this:
const express = require('express')
const multer = require('multer')
const path = require('path')
const bodyParser = require('body-parser')
const app = express()
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, path.join(__dirname, 'public'))
},
filename: (req, file, cb) => {
cb(null, Date.now() + '-' + file.originalname);
}
})
app.use(bodyParser.urlencoded({
extended: true
}));
const uploads = multer({
storage: storage
})
app.post('/upload', uploads.single('image'), (req, res) => {
console.log('uploaded:', req.file);
res.sendFile(req.file.path);
// or
//res.download(req.file.path);
})
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'))
});
app.listen(8000, () => console.log('Server Running at port: 8000'))