Spaces:
Paused
Paused
Commit ·
6ea4293
1
Parent(s): 2f11783
feat: implement advanced file sharing API with upload progress and wget support
Browse filesFiles changed (8)
- .gitignoreAdded+4
- DockerfileAdded+28
- README.md+21-10
- main.pyAdded+73
- requirements.txtAdded+4
- static/index.htmlAdded+51
- static/script.jsAdded+197
- static/style.cssAdded+242
1234uploads/__pycache__/*.pyc.env12345678910111213141516171819202122232425262728# Use an official Python runtime as a parent imageFROM python:3.9-slim
# Set the working directory in the containerWORKDIR /app
# Install system dependenciesRUN apt-get update && apt-get install -y \ build-essential \ && rm -rf /var/lib/apt/lists/*
# Copy the requirements file into the containerCOPY requirements.txt .
# Install any needed packages specified in requirements.txtRUN pip install --no-cache-dir -r requirements.txt
# Copy the rest of the application code into the containerCOPY . .
# Create uploads directory and set permissions for HF Spaces (UID 1000)RUN mkdir -p /app/uploads && chmod 777 /app/uploads
# Expose the port the app runs onEXPOSE 7860
# Define the command to run the appCMD ["python", "main.py"]12345678910---title: Filesharingemoji: 👀colorFrom: graycolorTo: bluesdk: dockerpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021# NexusShare - Advanced File Sharing APIThis is a high-performance, universal file sharing application designed for Hugging Face Spaces.## Features- **FastAPI Backend:** High performance and asynchronous.- **Modern UI:** Glassmorphism dark mode with responsive design.- **Drag & Drop:** Easy file uploading.- **Progress Tracking:** Real-time upload progress bars.- **Universal Support:** Share any file type.- **API Access:** Simple endpoints for programmatic access.## DeploymentThis project is ready for Hugging Face Spaces using the provided `Dockerfile`.The app runs on port `7860`.## API Endpoints- `GET /files`: List all files.- `POST /upload`: Upload files (multipart/form-data).- `GET /download/{filename}`: Download a specific file.- `DELETE /delete/{filename}`: Remove a file.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273import osimport shutilfrom fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasksfrom fastapi.responses import FileResponse, JSONResponsefrom fastapi.staticfiles import StaticFilesfrom typing import Listimport uuid
app = FastAPI(title="Advanced File Sharing API")
UPLOAD_DIR = "uploads"os.makedirs(UPLOAD_DIR, exist_ok=True)
# Mount static files for the frontendapp.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/")async def read_index(): return FileResponse("static/index.html")
@app.post("/upload")async def upload_files(files: List[UploadFile] = File(...)): uploaded_files = [] for file in files: file_id = str(uuid.uuid4())[:8] filename = f"{file_id}_{file.filename}" file_path = os.path.join(UPLOAD_DIR, filename) with open(file_path, "wb") as buffer: shutil.copyfileobj(file.file, buffer) uploaded_files.append({ "original_name": file.filename, "saved_name": filename, "size": os.path.getsize(file_path) }) return {"message": "Files uploaded successfully", "files": uploaded_files}
@app.get("/files")async def list_files(): files = [] for filename in os.listdir(UPLOAD_DIR): file_path = os.path.join(UPLOAD_DIR, filename) if os.path.isfile(file_path): files.append({ "name": filename, "display_name": "_".join(filename.split("_")[1:]), "size": os.path.getsize(file_path), "mtime": os.path.getmtime(file_path) }) # Sort by mtime descending files.sort(key=lambda x: x['mtime'], reverse=True) return files
@app.get("/download/{filename}")async def download_file(filename: str): file_path = os.path.join(UPLOAD_DIR, filename) if not os.path.exists(file_path): raise HTTPException(status_code=404, detail="File not found") return FileResponse(file_path, filename="_".join(filename.split("_")[1:]))
@app.delete("/delete/{filename}")async def delete_file(filename: str): file_path = os.path.join(UPLOAD_DIR, filename) if not os.path.exists(file_path): raise HTTPException(status_code=404, detail="File not found") os.remove(file_path) return {"message": "File deleted successfully"}
if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)1234fastapiuvicornpython-multipartaiofiles123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>NexusShare - Advanced File Sharing</title> <link rel="stylesheet" href="/static/style.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"></head><body> <div class="container"> <header> <h1><i class="fas fa-cloud-upload-alt"></i> NexusShare</h1> <p>Secure, Fast, and Universal File Sharing</p> </header>
<main> <div id="drop-zone" class="drop-zone"> <div class="drop-zone-content"> <i class="fas fa-file-import fa-3x"></i> <p>Drag & Drop files here or click to browse</p> <input type="file" id="file-input" multiple hidden> <button class="btn-primary" id="browse-btn">Select Files</button> </div> </div>
<div id="upload-progress-container" class="upload-progress-container hidden"> <h3>Uploading...</h3> <div id="progress-items"></div> </div>
<div class="file-list-section"> <div class="section-header"> <h2>Recent Files</h2> <button id="refresh-btn" class="btn-icon"><i class="fas fa-sync-alt"></i></button> </div> <div id="file-list" class="file-list"> <!-- Files will be loaded here --> <div class="loader">Loading files...</div> </div> </div> </main>
<footer> <p>© 2026 NexusShare. Powered by FastAPI.</p> </footer> </div>
<script src="/static/script.js"></script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197document.addEventListener('DOMContentLoaded', () => { const dropZone = document.getElementById('drop-zone'); const fileInput = document.getElementById('file-input'); const browseBtn = document.getElementById('browse-btn'); const fileList = document.getElementById('file-list'); const refreshBtn = document.getElementById('refresh-btn'); const progressContainer = document.getElementById('upload-progress-container'); const progressItems = document.getElementById('progress-items');
// Load initial file list loadFiles();
// Event Listeners browseBtn.addEventListener('click', () => fileInput.click()); fileInput.addEventListener('change', () => handleFiles(fileInput.files)); refreshBtn.addEventListener('click', loadFiles);
dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('drag-over'); });
dropZone.addEventListener('dragleave', () => { dropZone.classList.remove('drag-over'); });
dropZone.addEventListener('drop', (e) => { e.preventDefault(); dropZone.classList.remove('drag-over'); handleFiles(e.dataTransfer.files); });
async function handleFiles(files) { if (files.length === 0) return; progressContainer.classList.remove('hidden'); for (const file of files) { await uploadFile(file); } // Hide progress after a short delay if all done setTimeout(() => { progressContainer.classList.add('hidden'); progressItems.innerHTML = ''; loadFiles(); }, 2000); }
function uploadFile(file) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); const formData = new FormData(); formData.append('files', file);
// Create progress item UI const item = document.createElement('div'); item.className = 'progress-item'; item.innerHTML = ` <div class="progress-info"> <span>${file.name}</span> <span class="percent">0%</span> </div> <div class="progress-bar-bg"> <div class="progress-bar-fill"></div> </div> `; progressItems.appendChild(item);
const fill = item.querySelector('.progress-bar-fill'); const percent = item.querySelector('.percent');
xhr.upload.addEventListener('progress', (e) => { if (e.lengthComputable) { const p = Math.round((e.loaded / e.total) * 100); fill.style.width = p + '%'; percent.textContent = p + '%'; } });
xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200) { resolve(JSON.parse(xhr.responseText)); } else { reject(xhr.statusText); } } };
xhr.open('POST', '/upload', true); xhr.send(formData); }); }
async function loadFiles() { try { const response = await fetch('/files'); const files = await response.json(); renderFileList(files); } catch (error) { fileList.innerHTML = '<p class="error">Failed to load files.</p>'; } }
function renderFileList(files) { if (files.length === 0) { fileList.innerHTML = '<p class="empty-msg">No files uploaded yet.</p>'; return; }
const baseUrl = window.location.origin;
fileList.innerHTML = files.map(file => { const downloadUrl = `${baseUrl}/download/${file.name}`; const wgetCmd = `wget "${downloadUrl}"`; return ` <div class="file-item"> <div class="file-icon"> <i class="${getFileIcon(file.display_name)}"></i> </div> <div class="file-info"> <div class="file-name">${file.display_name}</div> <div class="file-meta">${formatBytes(file.size)} • ${new Date(file.mtime * 1000).toLocaleString()}</div> <div class="file-links"> <code class="direct-url" onclick="copyToClipboard('${downloadUrl}', 'URL')">${downloadUrl}</code> <code class="wget-cmd" onclick="copyToClipboard('${wgetCmd}', 'Command')">${wgetCmd}</code> </div> </div> <div class="file-actions"> <a href="/download/${file.name}" class="action-btn download-btn" title="Download"> <i class="fas fa-download"></i> </a> <button onclick="deleteFile('${file.name}')" class="action-btn delete-btn" title="Delete"> <i class="fas fa-trash"></i> </button> </div> </div> `;}).join(''); }
window.copyToClipboard = (text, label) => { navigator.clipboard.writeText(text).then(() => { alert(`${label} copied to clipboard!`); }); };
window.deleteFile = async (name) => { if (!confirm('Are you sure you want to delete this file?')) return; try { await fetch(`/delete/${name}`, { method: 'DELETE' }); loadFiles(); } catch (error) { alert('Failed to delete file'); } };
function getFileIcon(filename) { const ext = filename.split('.').pop().toLowerCase(); const icons = { pdf: 'fas fa-file-pdf', doc: 'fas fa-file-word', docx: 'fas fa-file-word', xls: 'fas fa-file-excel', xlsx: 'fas fa-file-excel', ppt: 'fas fa-file-powerpoint', pptx: 'fas fa-file-powerpoint', png: 'fas fa-file-image', jpg: 'fas fa-file-image', jpeg: 'fas fa-file-image', gif: 'fas fa-file-image', zip: 'fas fa-file-archive', rar: 'fas fa-file-archive', '7z': 'fas fa-file-archive', mp3: 'fas fa-file-audio', wav: 'fas fa-file-audio', mp4: 'fas fa-file-video', mkv: 'fas fa-file-video', txt: 'fas fa-file-alt', js: 'fas fa-file-code', html: 'fas fa-file-code', css: 'fas fa-file-code', py: 'fas fa-file-code' }; return icons[ext] || 'fas fa-file'; }
function formatBytes(bytes, decimals = 2) { if (bytes === 0) return '0 Bytes'; const k = 1024; const dm = decimals < 0 ? 0 : decimals; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; }});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242:root { --primary: #6366f1; --primary-hover: #4f46e5; --bg: #0f172a; --card-bg: #1e293b; --text: #f8fafc; --text-muted: #94a3b8; --border: #334155; --success: #22c55e; --danger: #ef4444;}
* { box-sizing: border-box; margin: 0; padding: 0;}
body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background-color: var(--bg); color: var(--text); line-height: 1.6; display: flex; justify-content: center; padding: 2rem;}
.container { width: 100%; max-width: 900px;}
header { text-align: center; margin-bottom: 3rem;}
header h1 { font-size: 2.5rem; color: var(--primary); margin-bottom: 0.5rem;}
header p { color: var(--text-muted);}
.drop-zone { background: var(--card-bg); border: 2px dashed var(--border); border-radius: 1rem; padding: 3rem; text-align: center; transition: all 0.3s ease; cursor: pointer; margin-bottom: 2rem;}
.drop-zone:hover, .drop-zone.drag-over { border-color: var(--primary); background: #1e293b80;}
.drop-zone-content i { color: var(--primary); margin-bottom: 1.5rem;}
.btn-primary { background: var(--primary); color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer; margin-top: 1rem; transition: background 0.2s;}
.btn-primary:hover { background: var(--primary-hover);}
.hidden { display: none; }
.upload-progress-container { background: var(--card-bg); border-radius: 1rem; padding: 1.5rem; margin-bottom: 2rem; border: 1px solid var(--border);}
.progress-item { margin-bottom: 1rem;}
.progress-info { display: flex; justify-content: space-between; margin-bottom: 0.5rem; font-size: 0.9rem;}
.progress-bar-bg { background: var(--border); height: 8px; border-radius: 4px; overflow: hidden;}
.progress-bar-fill { background: var(--primary); height: 100%; width: 0%; transition: width 0.1s;}
.file-list-section { background: var(--card-bg); border-radius: 1rem; padding: 1.5rem; border: 1px solid var(--border);}
.section-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;}
.btn-icon { background: none; border: none; color: var(--text-muted); cursor: pointer; font-size: 1.2rem; transition: color 0.2s;}
.btn-icon:hover { color: var(--primary); }
.file-list { display: flex; flex-direction: column; gap: 1rem;}
.file-item { display: flex; align-items: center; padding: 1rem; background: #0f172a; border-radius: 0.75rem; border: 1px solid var(--border);}
.file-icon { font-size: 1.5rem; margin-right: 1rem; color: var(--primary);}
.file-info { flex-grow: 1;}
.file-name { font-weight: 500; margin-bottom: 0.2rem; word-break: break-all;}
.file-links { display: flex; flex-direction: column; gap: 0.5rem; margin-top: 0.75rem;}
.file-links code { background: #020617; padding: 0.4rem 0.8rem; border-radius: 0.4rem; font-size: 0.75rem; color: var(--primary); border: 1px solid var(--border); cursor: pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: block; max-width: 100%;}
.file-links code:hover { border-color: var(--primary); background: #0f172a;}
.file-links code::before { content: attr(class); display: inline-block; width: 60px; font-weight: bold; text-transform: uppercase; font-size: 0.65rem; color: var(--text-muted); margin-right: 10px;} display: flex; gap: 0.5rem;}
.action-btn { padding: 0.5rem; border-radius: 0.4rem; border: none; cursor: pointer; transition: opacity 0.2s; color: white;}
.download-btn { background: var(--success); }.delete-btn { background: var(--danger); }
.action-btn:hover { opacity: 0.8; }
footer { text-align: center; margin-top: 4rem; color: var(--text-muted); font-size: 0.9rem;}
@media (max-width: 600px) { body { padding: 1rem; } .drop-zone { padding: 1.5rem; }}.gitignoreAdded+4
DockerfileAdded+28
README.md+21-10
main.pyAdded+73
requirements.txtAdded+4
static/index.htmlAdded+51
static/script.jsAdded+197
static/style.cssAdded+242