multer
multer copied to clipboard
ERROR UPLOADING FILE using the javascript and I also use multer in handling the fileupload
what are the error of my code ?
"this is the upload photo code
const express = require('express'); const multer = require('multer'); const path = require('path'); const { DB_CURRENT_TIMESTAMP, queryDb } = require('@api/utils/mysql');
//const app = express(); //const port = process.env.SERVER_PORT || 3000; const router = express.Router();
// Set up storage for uploaded files const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, '../assets/uploads'); }, filename: function (req, file, cb) { const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9); const fileExtension = path.extname(file.originalname); cb(null, file.fieldname + '-' + uniqueSuffix + fileExtension); } });
const upload = multer({ storage: storage });
// Serve uploaded files statically //app.use('/uploads', express.static('uploads')); router.use('/uploads', express.static('uploads'));
// Handle file upload router.post('/api/upload-photo', upload.single('image'), async (req, res) => { if (!req.file) { return res.status(400).json({ message: 'No file uploaded' }); }
// You can perform additional logic here, like saving the file path to a database // and returning a response.
try {
const { image = '' } = req.body;
if (!image) {
return res.status(400).json({
message: 'Please select an Image.',
});
}
const imagePath = `/uploads/${req.file.filename}`; // Update the path to match your file storage location
// Save file path to the database
await queryDb(`
INSERT INTO gallery (date_uploaded, image) VALUES (?, ?)`,
[DB_CURRENT_TIMESTAMP, imagePath]
);
return res.status(200).json({
message: 'Image Uploaded!'
});
} catch (err) {
res.status(500).json({
message: `Server error : ${err.message}`
});
}
res.status(200).json({ message: 'Image Uploaded' }); });
// app.listen(port, () => {
// console.log(Server is running on port ${port});
// });
module.exports = router;
and these are the "get gallery data" code
//get all gallery
const { queryDb } = require('@api/utils/mysql');
module.exports = async function(req, res) { try { var {
} = req.body;
message= '';
var gallery = await queryDb('SELECT * FROM gallery');
return res.status(200).json ({
gallery
});
}
catch(err) {
// console.log(err.message);
res.status(500).json({
message: `Server error : ${err.message}`
});
}
}
You didn't attach the specific error you got, but as far as I can see:
- the row
const { image = '' } = req.body;and returning 400 might be not necessary - since you already handle the
imagefield in the request by theif (!req.file) { - Middleware
upload.single('image')will take theimagefield from the body and populate thereq.file
This is the error of my code, i don’t know what is the wrong of code.
I am having a error too, I dont understand what I am doing wrong
Error: Error: ENOENT: no such file or directory, open 'C:\Users.......src\routes\uploads\product_file-1693576521663.xlsx'
const path = require('path'); const multer = require('multer'); let storage = multer.diskStorage({ destination: function (req, file, cb) { // Create the uploads folder if it does not exist if (!fs.existsSync('./uploads')) { fs.mkdirSync('./uploads'); } cb(null, './uploads/'); }, filename: function (req, file, cb) { let datetimestamp = Date.now(); cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1]); } }); const upload2 = multer({ storage: storage, }); const upload = multer();
routes.post('/product-file-upload',upload2.single('product_file'),require('../controllers/products/updateSwagProducts')); //routes.post('/product-file-upload',upload.single('product_file'),require('../controllers/products/updateSwagProducts'));
The file contents are coming through the request but I somehow cant save it, even though I have created the uploads folder
Post the html that you're using.