gpt-4.1-mini-2025-04-14· OpenAI
LMArena Human Preference 140K
write a full web application. it should be a file hosting website each user can have…
- User
write a full web application. it should be a file hosting website each user can have their files uploaded on it. they can share a link to their files on social media and can earn money by this each user have a analytics dashboard to see the views, downloads, earning
- Assistant
Creating a full web application for a file hosting service with user accounts, file uploads, sharing links, earnings, and analytics is a complex project. Below, I will provide a simplified but complete example using modern web technologies:
- Backend: Node.js with Express and MongoDB (via Mongoose)
- Frontend: React
- Authentication: JWT (JSON Web Tokens)
- File Storage: Local filesystem (for simplicity; in production, use cloud storage like AWS S3)
- Analytics: Track views/downloads and calculate earnings
- Earnings: Simple fixed rate per download/view
Features implemented in this example:
- User registration/login
- File upload per user
- Generate shareable links
- Track views and downloads
- Simple earnings calculation
- User dashboard with analytics
1. Backend (Node.js + Express + MongoDB)
Setup
mkdir file-hosting-app cd file-hosting-app npm init -y npm install express mongoose bcryptjs jsonwebtoken multer cors dotenvCreate a
.envfile:PORT=4000 MONGO_URI=mongodb://localhost:27017/filehosting JWT_SECRET=your_jwt_secret EARNING_RATE=0.05 # $0.05 per download
server.jsrequire('dotenv').config(); const express = require('express'); const mongoose = require('mongoose'); const cors = require('cors'); const authRoutes = require('./routes/auth'); const fileRoutes = require('./routes/files'); const app = express(); app.use(cors()); app.use(express.json()); app.use('/uploads', express.static('uploads')); // serve uploaded files app.use('/api/auth', authRoutes); app.use('/api/files', fileRoutes); const PORT = process.env.PORT || 4000; mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log('MongoDB connected'); app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); }) .catch(err => console.error(err));
Models
Create a folder
modelsand add:User.jsconst mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ username: { type: String, unique: true }, email: { type: String, unique: true }, password: String, earnings: { type: Number, default: 0 } }); module.exports = mongoose.model('User', userSchema);File.jsconst mongoose = require('mongoose'); const fileSchema = new mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, filename: String, originalname: String, views: { type: Number, default: 0 }, downloads: { type: Number, default: 0 }, createdAt: { type: Date, default: Date.now } }); module.exports = mongoose.model('File', fileSchema);
Middleware for auth:
middleware/auth.jsconst jwt = require('jsonwebtoken'); module.exports = function(req, res, next) { const token = req.header('Authorization')?.split(' ')[1]; if (!token) return res.status(401).json({ message: 'No token, authorization denied' }); try { const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = decoded.user; next(); } catch (err) { res.status(401).json({ message: 'Token is not valid' }); } };
Routes
Create folder
routesauth.jsconst express = require('express'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const User = require('../models/User'); const router = express.Router(); // Register router.post('/register', async (req, res) => { const { username, email, password } = req.body; try { let user = await User.findOne({ email }); if (user) return res.status(400).json({ message: 'User already exists' }); user = new User({ username, email, password: await bcrypt.hash(password, 10) }); await user.save(); const payload = { user: { id: user.id } }; const token = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '1d' }); res.json({ token }); } catch (err) { res.status(500).send('Server error'); } }); // Login router.post('/login', async (req, res) => { const { email, password } = req.body; try { const user = await User.findOne({ email }); if (!user) return res.status(400).json({ message: 'Invalid credentials' }); const isMatch = await bcrypt.compare(password, user.password); if (!isMatch) return res.status(400).json({ message: 'Invalid credentials' }); const payload = { user: { id: user.id } }; const token = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '1d' }); res.json({ token }); } catch (err) { res.status(500).send('Server error'); } }); module.exports = router;
files.jsconst express = require('express'); const multer = require('multer'); const auth = require('../middleware/auth'); const File = require('../models/File'); const User = require('../models/User'); const path = require('path'); const fs = require('fs'); const router = express.Router(); const upload = multer({ dest: 'uploads/', limits: { fileSize: 100 * 1024 * 1024 } // 100MB limit }); // Upload file router.post('/upload', auth, upload.single('file'), async (req, res) => { try { const file = new File({ user: req.user.id, filename: req.file.filename, originalname: req.file.originalname }); await file.save(); res.json({ message: 'File uploaded', fileId: file._id }); } catch (err) { res.status(500).send('Server error'); } }); // Get user's files router.get('/myfiles', auth, async (req, res) => { try { const files = await File.find({ user: req.user.id }); res.json(files); } catch (err) { res.status(500).send('Server error'); } }); // Download file by id (public) router.get('/download/:id', async (req, res) => { try { const file = await File.findById(req.params.id); if (!file) return res.status(404).json({ message: 'File not found' }); // Increment downloads and earnings file.downloads++; await file.save(); const user = await User.findById(file.user); user.earnings += parseFloat(process.env.EARNING_RATE); await user.save(); const filepath = path.join(__dirname, '..', 'uploads', file.filename); res.download(filepath, file.originalname); } catch (err) { res.status(500).send('Server error'); } }); // View file info (simulate view count) router.get('/view/:id', async (req, res) => { try { const file = await File.findById(req.params.id); if (!file) return res.status(404).json({ message: 'File not found' }); file.views++; await file.save(); const user = await User.findById(file.user); user.earnings += parseFloat(process.env.EARNING_RATE) / 10; // smaller earning for views await user.save(); res.json({ message: 'View counted' }); } catch (err) { res.status(500).send('Server error'); } }); // Get analytics dashboard router.get('/dashboard', auth, async (req, res) => { try { const files = await File.find({ user: req.user.id }); const user = await User.findById(req.user.id); const analytics = files.map(f => ({ id: f._id, originalname: f.originalname, views: f.views, downloads: f.downloads })); res.json({ earnings: user.earnings.toFixed(2), files: analytics }); } catch (err) { res.status(500).send('Server error'); } }); module.exports = router;
2. Frontend (React)
Create React app:
npx create-react-app client cd client npm install axios react-router-dom
src/App.jsimport React from 'react'; import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom'; import Register from './Register'; import Login from './Login'; import Dashboard from './Dashboard'; import Upload from './Upload'; function App() { return ( <Router> <nav> <Link to="/">Dashboard</Link> | <Link to="/upload">Upload</Link> | <Link to="/login">Login</Link> | <Link to="/register">Register</Link> </nav> <Routes> <Route path="/" element={<Dashboard />} /> <Route path="/upload" element={<Upload />} /> <Route path="/login" element={<Login />} /> <Route path="/register" element={<Register />} /> </Routes> </Router> ); } export default App;
src/Register.jsimport React, { useState } from 'react'; import axios from 'axios'; export default function Register() { const [form, setForm] = useState({ username: '', email: '', password: '' }); const [message, setMessage] = useState(''); const onChange = e => setForm({ ...form, [e.target.name]: e.target.value }); const onSubmit = async e => { e.preventDefault(); try { const res = await axios.post('http://localhost:4000/api/auth/register', form); localStorage.setItem('token', res.data.token); setMessage('Registered successfully!'); } catch (err) { setMessage(err.response?.data?.message || 'Error'); } }; return ( <form onSubmit={onSubmit}> <h2>Register</h2> <input name="username" placeholder="Username" onChange={onChange} required /> <input name="email" type="email" placeholder="Email" onChange={onChange} required /> <input name="password" type="password" placeholder="Password" onChange={onChange} required /> <button type="submit">Register</button> <p>{message}</p> </form> ); }
src/Login.jsimport React, { useState } from 'react'; import axios from 'axios'; export default function Login() { const [form, setForm] = useState({ email: '', password: '' }); const [message, setMessage] = useState(''); const onChange = e => setForm({ ...form, [e.target.name]: e.target.value }); const onSubmit = async e => { e.preventDefault(); try { const res = await axios.post('http://localhost:4000/api/auth/login', form); localStorage.setItem('token', res.data.token); setMessage('Logged in successfully!'); } catch (err) { setMessage(err.response?.data?.message || 'Error'); } }; return ( <form onSubmit={onSubmit}> <h2>Login</h2> <input name="email" type="email" placeholder="Email" onChange={onChange} required /> <input name="password" type="password" placeholder="Password" onChange={onChange} required /> <button type="submit">Login</button> <p>{message}</p> </form> ); }
src/Upload.jsimport React, { useState } from 'react'; import axios from 'axios'; export default function Upload() { const [file, setFile] = useState(null); const [message, setMessage] = useState(''); const onChange = e => setFile(e.target.files[0]); const onSubmit = async e => { e.preventDefault(); if (!file) return setMessage('Select a file first'); const formData = new FormData(); formData.append('file', file); try { const token = localStorage.getItem('token'); const res = await axios.post('http://localhost:4000/api/files/upload', formData, { headers: { 'Content-Type': 'multipart/form-data', Authorization: `Bearer ${token}` } }); setMessage('File uploaded! ID: ' + res.data.fileId); } catch (err) { setMessage(err.response?.data?.message || 'Error uploading'); } }; return ( <form onSubmit={onSubmit}> <h2>Upload File</h2> <input type="file" onChange={onChange} /> <button type="submit">Upload</button> <p>{message}</p> </form> ); }
src/Dashboard.jsimport React, { useEffect, useState } from 'react'; import axios from 'axios'; export default function Dashboard() { const [files, setFiles] = useState([]); const [earnings, setEarnings] = useState('0.00'); const [message, setMessage] = useState(''); useEffect(() => { const fetchDashboard = async () => { try { const token = localStorage.getItem('token'); if (!token) { setMessage('Please login to see dashboard'); return; } const res = await axios.get('http://localhost:4000/api/files/dashboard', { headers: { Authorization: `Bearer ${token}` } }); setFiles(res.data.files); setEarnings(res.data.earnings); } catch (err) { setMessage('Error fetching dashboard'); } }; fetchDashboard(); }, []); return ( <div> <h2>Dashboard</h2> <p>Earnings: ${earnings}</p> {message && <p>{message}</p>} <table border="1" cellPadding="5"> <thead> <tr> <th>File Name</th> <th>Views</th> <th>Downloads</th> <th>Share Link</th> </tr> </thead> <tbody> {files.map(f => ( <tr key={f.id}> <td>{f.originalname}</td> <td>{f.views}</td> <td>{f.downloads}</td> <td> <input type="text" readOnly value={`http://localhost:4000/api/files/download/${f.id}`} style={{ width: '300px' }} onFocus={e => e.target.select()} /> </td> </tr> ))} </tbody> </table> </div> ); }
How to run
- Start MongoDB locally or use a cloud MongoDB.
- Run backend:
node server.js- Run frontend:
cd client npm start
Notes
- This is a basic prototype. For production:
- Use cloud storage (AWS S3, Google Cloud Storage)
- Add proper error handling and validation
- Secure file uploads (check file types, virus scanning)
- Use HTTPS
- Add pagination for dashboard files
- Add payment integration for earnings withdrawal
- Add rate limiting and abuse prevention
- Improve UI/UX
If you want, I can help you extend this with more features or deployment instructions!