Now add a backend for it
- User
Now add a backend for it
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Now add a backend for it
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To add a backend to the media file drop zone web app, we'll use Node.js with Express for the server and Multer for handling file uploads. The backend will handle file uploads, store them temporarily, and allow for file deletion. Here's how you can extend the previous app with a backend:
media-drop-app/
├── public/
│ ├── index.html
│ ├── style.css
│ └── script.js
├── uploads/
├── server.js
├── package.json
└── README.md
First, create a new directory for your project and initialize a Node.js project:
mkdir media-drop-app
cd media-drop-app
npm init -y
Install the necessary dependencies:
npm install express multer cors
server.js)Create a file named server.js in the root of your project directory with the following content:
const express = require('express');
const multer = require('multer');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const app = express();
const port = 3000;
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static('public'));
app.use('/uploads', express.static('uploads'));
// Configure Multer for file uploads
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});
const upload = multer({ storage: storage });
// Ensure uploads directory exists
if (!fs.existsSync('uploads')) {
fs.mkdirSync('uploads');
}
// Routes
app.post('/upload', upload.array('files'), (req, res) => {
const files = req.files.map(file => ({
name: file.originalname,
size: file.size,
path: `/uploads/${file.filename}`
}));
res.json({ files });
});
app.delete('/delete/:filename', (req, res) => {
const filePath = path.join(__dirname, 'uploads', req.params.filename);
fs.unlink(filePath, (err) => {
if (err) {
return res.status(500).json({ error: 'Failed to delete file' });
}
res.json({ message: 'File deleted successfully' });
});
});
app.delete('/delete-all', (req, res) => {
const directory = path.join(__dirname, 'uploads');
fs.readdir(directory, (err, files) => {
if (err) {
return res.status(500).json({ error: 'Failed to read directory' });
}
for (const file of files) {
fs.unlink(path.join(directory, file), err => {
if (err) console.error(err);
});
}
res.json({ message: 'All files deleted successfully' });
});
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Now, update the frontend to interact with the backend. Move the HTML, CSS, and JavaScript into separate files under the public directory.
public/index.html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Media File Drop Zone</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>Media File Drop Zone</h1>
<div id="dropZone" class="drop-zone">
<p>Drag and drop media files here</p>
</div>
<div id="fileList" class="file-list">
<!-- Files will be displayed here -->
</div>
<button id="clearAll" class="clear-all">Clear All</button>
</div>
<script src="script.js"></script>
</body>
</html>
public/style.cssbody {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f4f4f4;
}
.container {
max-width: 800px;
margin: 0 auto;
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.drop-zone {
border: 2px dashed #ccc;
border-radius: 8px;
padding: 20px;
text-align: center;
margin-bottom: 20px;
transition: background-color 0.3s;
}
.drop-zone.highlight {
background-color: #e6f7ff;
border-color: #1890ff;
}
.file-list {
display: flex;
flex-direction: column;
gap: 10px;
}
.file-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
background-color: #f9f9f9;
}
.file-item button {
background-color: #ff4d4f;
color: white;
border: none;
border-radius: 4px;
padding: 5px 10px;
cursor: pointer;
}
.file-item button:hover {
background-color: #ff7875;
}
.clear-all {
margin-top: 20px;
background-color: #ff4d4f;
color: white;
border: none;
border-radius: 4px;
padding: 10px 20px;
cursor: pointer;
}
.clear-all:hover {
background-color: #ff7875;
}
public/script.jsdocument.addEventListener('DOMContentLoaded', function() {
const dropZone = document.getElementById('dropZone');
const fileList = document.getElementById('fileList');
const clearAllButton = document.getElementById('clearAll');
let files = [];
// Prevent default drag behaviors
dropZone.addEventListener('dragover', function(e) {
e.preventDefault();
dropZone.classList.add('highlight');
});
dropZone.addEventListener('dragleave', function() {
dropZone.classList.remove('highlight');
});
dropZone.addEventListener('drop', function(e) {
e.preventDefault();
dropZone.classList.remove('highlight');
const droppedFiles = e.dataTransfer.files;
handleFiles(droppedFiles);
});
// Handle files when dropped
async function handleFiles(droppedFiles) {
const formData = new FormData();
for (let i = 0; i < droppedFiles.length; i++) {
const file = droppedFiles[i];
if (isMediaFile(file)) {
formData.append('files', file);
}
}
try {
const response = await fetch('http://localhost:3000/upload', {
method: 'POST',
body: formData
});
const result = await response.json();
result.files.forEach(file => {
files.push(file);
displayFile(file);
});
} catch (error) {
console.error('Error uploading files:', error);
}
}
// Check if the file is a media file (image, video, audio)
function isMediaFile(file) {
const mediaTypes = ['image/', 'video/', 'audio/'];
return mediaTypes.some(type => file.type.startsWith(type));
}
// Display a file in the file list
function displayFile(file) {
const fileItem = document.createElement('div');
fileItem.className = 'file-item';
const fileInfo = document.createElement('div');
fileInfo.textContent = `${file.name} (${formatFileSize(file.size)})`;
const removeButton = document.createElement('button');
removeButton.textContent = 'Remove';
removeButton.addEventListener('click', async function() {
await removeFile(file);
fileItem.remove();
});
fileItem.appendChild(fileInfo);
fileItem.appendChild(removeButton);
fileList.appendChild(fileItem);
}
// Format file size in a human-readable format
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
// Remove a specific file
async function removeFile(fileToRemove) {
try {
const filename = fileToRemove.path.split('/').pop();
await fetch(`http://localhost:3000/delete/${filename}`, {
method: 'DELETE'
});
files = files.filter(file => file !== fileToRemove);
} catch (error) {
console.error('Error deleting file:', error);
}
}
// Clear all files
clearAllButton.addEventListener('click', async function() {
try {
await fetch('http://localhost:3000/delete-all', {
method: 'DELETE'
});
files = [];
fileList.innerHTML = '';
} catch (error) {
console.error('Error deleting all files:', error);
}
});
});
package.jsonAdd a start script to your package.json:
{
"name": "media-drop-app",
"version": "1.0.0",
"description": "A web app for dropping and managing media files",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"cors": "^2.8.5",
"express": "^4.17.1",
"multer": "^1.4.2"
}
}
npm start
http://localhost:3000.Backend (server.js):
uploads directory./upload), deleting a specific file (/delete/:filename), and deleting all files (/delete-all).public directory and uploaded files from the uploads directory.Frontend (public/script.js):
fetch API to communicate with the backend for uploading, deleting, and clearing files.CORS: Added to allow cross-origin requests between the frontend and backend.
This setup provides a complete web app with a backend for handling media file uploads and deletions. Remember to handle file storage securely in a production environment, possibly using a cloud storage service instead of local disk storage.