Sep 7, 2024
0
Level 1
Problem uploading images with Dropzone
bookRoute
router.post('/upload', authMiddleware.authenticateUser, upload.single('image'), bookController.uploadFile);
router
.route('/uploader')
.get(authMiddleware.authenticateUser, bookController.getBooksByUploader);
bookController
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 {
const { name, author, description, page, image } = req.body;
const uploader = req.user._id;
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 image = req.file ? req.file.path : null;
console.log('Image path:', image || 'No file');
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' });
}
}
};
onMounted(() => {
const modalElement = document.getElementById("modal-main");
if (modalElement) {
modal = new $bootstrap.Modal(modalElement);
}
bookStore.fetchBooksByUploader();
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", // Param name should match with multer's expected field name
acceptedFiles: "image/*",
autoProcessQueue: false, // Disable automatic file uploads
init: function () {
this.on("sending", (file, xhr, formData) => {
xhr.setRequestHeader("Authorization", `Bearer ${authStore.token}`);
// formData.append("name", newBook.name);
// formData.append("author", newBook.author);
// formData.append("description", newBook.description);
// formData.append("page", newBook.page);
});
this.on("success", (file, response) => {
// Handle success
console.log("File uploaded successfully", response);
newBook.image = response.filePath;
});
this.on("error", (file, message) => {
// Handle error
console.error("Upload failed:", message);
});
},
});
}
});
const addBook = async () => {
try {
await new Promise((resolve, reject) => {
dropzone.on("complete", (file) => {
if (file.status === 'success') {
resolve();
} else {
reject(new Error("File upload failed"));
}
});
dropzone.processQueue();
});
await bookStore.addBook(newBook);
currentPage.value = 1;
modal?.hide();
Object.assign(newBook, {
name: "",
author: "",
description: "",
page: null,
image: null,
editedBookId: null,
});
await bookStore.fetchBooksByUploader();
showToast("New book added successfully", {
type: "success",
position: "top-right",
timeout: 1000,
});
} catch (error) {
console.log(error);
showToast("Failed to add book", {
type: "error",
position: "top-right",
timeout: 3000,
});
}
};
I did this but I didn't want to take a picture
const { name, author, description, page, image } = req.body;
It seems like it should be saved with req.file instead, right?
Please or to participate in this conversation.