Java journal practice

 

 

Announcements and Recent Posts

Older Posts

 

const express = require(\'express\');
const bodyParser = require(\'body-parser\');
const mysql = require(\'mysql\');
const path = require(\'path\');
const multer = require(\'multer\');
const fs = require(\'fs\');

const app = express();
const port = 3000;

// Set up body-parser middleware
app.use(bodyParser.json());

// Serve static files
app.use(express.static(path.join(__dirname)));

// Create MySQL connection
const connection = mysql.createConnection({
host: \'localhost\',
user: \'root\',
password: \'root\',
database: \'journal_db\'
});

// Connect to MySQL
connection.connect((err) => {
if (err) {
console.error(\'Error connecting to MySQL: \', err);
return;
}
console.log(\'Connected to MySQL\');
});

// Configure multer for file uploads (storage in memory)
const storage = multer.memoryStorage();
const upload = multer({ storage });

// Handle form submission
app.post(\'/submit\', upload.single(\'file\'), (req, res) => {
const { title } = req.body;
const file = req.file.buffer; // This contains the file data as a Buffer

const sql = \'INSERT INTO journal (title, file) VALUES (?, ?)\';
connection.query(sql, [title, file], (err, result) => {
if (err) {
return res.json({ success: false, error: err.message });
}
res.json({ success: true });
});
console.log(\'File uploaded\');
});

// Fetch journal entries
app.get(\'/entries\', (req, res) => {
const sql = \'SELECT id, title FROM journal\';
connection.query(sql, (err, rows) => {
if (err) {
throw err;
}
res.json(rows);
});
});

// Fetch a specific journal entry (to download the file)
app.get(\'/entries/:id\', (req, res) => {
const sql = \'SELECT title, file FROM journal WHERE id = ?\';
connection.query(sql, [req.params.id], (err, rows) => {
if (err) {
throw err;
}
if (rows.length > 0) {
const fileData = rows[0].file;
const fileName = rows[0].title + \'.pdf\'; // Assuming the file is a PDF
const filePath = path.join(__dirname, fileName);

// Save the file
fs.writeFile(filePath, fileData, \'binary\', (err) => {
if (err) {
throw err;
}
res.download(filePath, fileName, (err) => {
if (err) {
throw err;
}
// // Delete the file after download
// fs.unlink(filePath, (err) => {
// if (err) {
// throw err;
// }
// console.log(\'File deleted\');
// });
});
});
} else {
res.status(404).send(\'File not found\');
}
});
});

// Start the server
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});