Reputation: 11
I am making a project in frontend (nuxt 3) and backend (nodejs), my codes are as follows.
I can't understand why no uplaoding image path on database.
This is backend side
This is upload utils file
utils/fileUpload.js
import multer from "multer";
import path from "path";
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads');
},
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname));
}
});
const upload = multer({
storage,
fileFilter: (req, file, cb) => {
if(file.mimetype === 'image/png' || file.mimetype === 'image/jpg' || file.mimetype === 'image/jpeg' || file.mimetype === 'image/gif') {
cb(null, true);
}else {
cb(new Error('MimeType not supported'), false);
}
},
});
export default upload;
This is route which I post request upload file
bookRoute.js
router.post('/upload', authMiddleware.authenticateUser, upload.single('image'), bookController.uploadFile);
This is controller
bookController.js
This is controller which I post request fron dropzone file upload.
const uploadFile = async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded' });
}
const filePath = req.file.path;
res.status(200).json({ message: 'File uploaded successfully', filePath });
} catch (error) {
console.error('Error uploading file', error);
res.status(500).json({ error: 'Internal Server ERROR' });
}
};
const store = async (req, res) => {
try {
upload.single('image')(req, res, async (err) => {
if (err) {
return res.status(400).json({ error: err.message });
}
const { name, author, description, page } = req.body;
const uploader = req.user._id;
const image = req.file ? req.file.path : null;
console.log('Uploaded file:', req.file);
console.log('Image path:', image || 'No file');
if (!image) { // Check if image was uploaded
return res.status(400).json({ error: 'Image upload failed.' });
}
const existingBook = await Book.findOne({ name, author });
if (existingBook) {
return res.status(400).json({ error: 'A book with same name and author already exist!' });
};
const newBook = await Book.create({
name,
author,
description,
page,
uploader,
image
});
return res.status(201).json({
message: 'Book created successfully',
books: newBook
});
});
} catch (error) {
// Handle validation errors
if (error.name === 'ValidationError') {
if (checkValidationErrors(error, res)) return;
} else {
console.error("Error at creating book", error);
return res
.status(500)
.json({ error: 'Internal Server ERROR' });
}
}
};
This is frontend side
DashboardBooks.vue
onMounted(() => {
if (dropzoneElement.value) {
dropzone = new Dropzone(dropzoneElement.value, {
url: "http://localhost:5000/api/v1/books/upload",
thumbnailWidth: 150,
maxFilesize: 2, // Max file size in MB
dictDefaultMessage: "Drag files here or click to upload",
paramName: "image",
acceptedFiles: "image/*",
init: function () {
this.on("sending", (file, xhr, formData) => {
xhr.setRequestHeader("Authorization", `Bearer ${authStore.token}`);
});
this.on("success", (file, response) => {
// Handle success
console.log("File uploaded successfully", response);
});
this.on("error", (file, message) => {
// Handle error
console.error("Upload failed:", message);
});
},
});
}
});
The photo does not load in the console
File uploaded successfully {message: 'File uploaded successfully', filePath: 'uploads/1725613201618.jpg'}
console.log('Uploaded file:', req.file);
console.log('Image path:', image || 'No file');
Server listening on 5000
Uploaded file: undefined
Image path: No file
console.log('Uploaded file:', req.file);
console.log('Image path:', image || 'No file');
Server listening on 5000
Uploaded file: undefined
Image path: No file
Upvotes: 0
Views: 121