const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const port = 3000;
// Настройка хранилища для Multer
const storage = multer.diskStorage({
destination: (req, file, cb) => {
// Папка, куда будут сохраняться изображения
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
// Уникальное имя файла (оригинальное имя + текущая временная метка)
const ext = path.extname(file.originalname); // Получаем расширение файла
cb(null, file.fieldname + '-' + Date.now() + ext);
}
});
// Создание экземпляра Multer с настройками хранилища
const upload = multer({ storage: storage });
// Создайте папку "uploads" если ее еще нет
const fs = require('fs');
const uploadDir = path.join(__dirname, 'uploads'); // Absolute path to upload directory
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
// Маршрут для загрузки
app.post('/api/upload', upload.single('itemImage'), (req, res) => {
if (!req.file) {
return res.status(400).send('Необходимо загрузить изображение.');
}
// Данные формы доступны в req.body
const itemName = req.body.itemName;
const itemDescription = req.body.itemDescription;
const itemPrice = req.body.itemPrice;
const itemCategory = req.body.itemCategory;
// Информация о файле доступна в req.file
const imagePath = req.file.path; // Путь к сохраненному изображению
console.log('Название:', itemName);
console.log('Описание:', itemDescription);
console.log('Цена:', itemPrice);
console.log('Категория:', itemCategory);
console.log('Путь к изображению:', imagePath);
// Здесь должна быть логика сохранения данных в базу данных
// (например, с использованием MongoDB, PostgreSQL и т.д.)
res.json({ message: 'Файл успешно загружен и данные сохранены!', filePath: imagePath });
});
// Обработка ошибок загрузки
app.use((err, req, res, next) => {
console.error(err.stack);
if (err instanceof multer.MulterError) {
// A Multer error occurred when uploading.
res.status(400).send(err.message);
} else if (err) {
// An unknown error occurred when uploading.
res.status(500).send('Internal Server Error');
} else {
next();
}
});
app.listen(port, () => {
console.log(`Сервер запущен на порту ${port}`);
});
form.addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(form);
try {
const response = await fetch('http://localhost:3000/api/upload', { // Изменено
method: 'POST',
body: formData
});
const data = await response.json();
console.log('Успех:', data);
// Обновление UI с информацией об успешной загрузке
alert(data.message + ' Файл сохранен по адресу: ' + data.filePath);
} catch (error) {
console.error('Ошибка:', error);
alert('Ошибка при загрузке файла: ' + error.message);
}
});