To save a copy of the selected items text file to a directory named saves with the filename <email_address>.txt, you'll need a server-side component. This is because client-side JavaScript running in the browser cannot write files to the server's filesystem directly due to security restrictions.
Here's a complete solution using Node.js with Express to handle the server-side logic. This example assumes you have Node.js installed.
Project Structure
/catalog/
│
├── index.html
├── items.txt
├── images/
│ ├── item1.jpg
│ ├── item2.jpg
│ └── ... (more .jpg files)
├── saves/
│ └── (this directory will contain saved files)
├── server.js
└── package.json
Step-by-Step Implementation
1. Initialize a Node.js Project
Open your terminal, navigate to the catalog directory, and run:
npm init -y
2. Install Required Packages
Install Express and other necessary packages:
npm install express body-parser fs
3. Create server.js
Create a file named server.js in the catalog directory with the following content:
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const app = express();
const PORT = 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname)));
app.get('/items.txt', (req, res) => {
res.sendFile(path.join(__dirname, 'items.txt'));
});
app.post('/submit', (req, res) => {
const { email, selectedItems } = req.body;
if (!email || !selectedItems || selectedItems.length === 0) {
return res.status(400).send('Invalid request');
}
const fileContent = `Thank you for your interest, ${email}!\n\nYou have selected the following items:\n\n${selectedItems.join('\n')}`;
const filePath = path.join(__dirname, 'saves', `${email}.txt`);
fs.writeFile(filePath, fileContent, (err) => {
if (err) {
return res.status(500).send('Error saving file');
}
res.download(filePath, (err) => {
if (err) {
console.error('Error downloading file:', err);
}
fs.unlink(filePath, (err) => {
if (err) {
console.error('Error deleting file:', err);
}
});
});
});
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
4. Update index.html
Update your index.html to send the selected items to the server:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Item Catalog</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
.item { border: 1px solid #ccc; padding: 10px; margin-bottom: 10px; display: flex; gap: 20px; align-items: center; }
.item img { max-width: 150px; height: auto; }
.item-description { flex-grow: 1; }
input[type="email"] { width: 300px; padding: 5px; margin-bottom: 20px; }
button { padding: 10px 20px; font-size: 16px; }
</style>
</head>
<body>
<h1>Item Selection</h1>
<label for="email">Enter your email:</label><br>
<input type="email" id="email" placeholder="example@example.com" required><br><br>
<div id="items"></div>
<button onclick="submitSelection()">Send</button>
<script>
async function loadItems() {
try {
const response = await fetch('/items.txt');
const text = await response.text();
const lines = text.trim().split('\n');
const itemsContainer = document.getElementById('items');
lines.forEach((line, index) => {
const [filename, description] = line.split('|');
const itemDiv = document.createElement('div');
itemDiv.classList.add('item');
itemDiv.innerHTML = `
<img src="images/${filename}" alt="Item image">
<div class="item-description">
<p>${description}</p>
<label>
<input type="checkbox" class="item-checkbox" data-description="${description}">
Interested
</label>
</div>
`;
itemsContainer.appendChild(itemDiv);
});
} catch (err) {
console.error('Error loading items:', err);
}
}
function submitSelection() {
const email = document.getElementById('email').value;
const checkboxes = document.querySelectorAll('.item-checkbox:checked');
if (!email) {
alert('Please enter your email address.');
return;
}
if (checkboxes.length === 0) {
alert('Please select at least one item.');
return;
}
const selectedItems = Array.from(checkboxes).map(cb => cb.getAttribute('data-description'));
fetch('/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, selectedItems }),
})
.then(response => response.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = `${email}.txt`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
alert('File downloaded and saved successfully!');
})
.catch(error => {
console.error('Error:', error);
alert('There was an error submitting your selection.');
});
}
// Load items on page load
window.onload = loadItems;
</script>
</body>
</html>
Running the Server
- Make sure you have Node.js installed.
- Navigate to the
catalog directory in your terminal.
- Run the server using:
node server.js
- Open your browser and navigate to
http://localhost:3000.
This setup will allow users to select items, download a text file with their selections, and save a copy of that file on the server in the saves directory with the filename <email_address>.txt.