CoolFace
Apppublic

Zhofang/temp_storage

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
temp.js281 linesDownload Raw Back to root
1const express = require('express');2const fs = require('fs');3const path = require('path');4const multer = require('multer');5 6const app = express();7const uploadDir = path.join(__dirname, 'uploads');8 9// Ensure uploads directory exists10if (!fs.existsSync(uploadDir)) {11    fs.mkdirSync(uploadDir);12}13 14// Function to generate a short random ID (alphanumeric)15function generateShortId() {16    return Math.random().toString(36).substring(2, 7); // Generates a random string of length 517}18 19// Configure multer for file storage20const storage = multer.diskStorage({21    destination: function (req, file, cb) {22        cb(null, uploadDir);23    },24    filename: function (req, file, cb) {25        const shortId = generateShortId();26        cb(null, `${shortId}-${file.originalname}`);27    }28});29 30const upload = multer({ storage: storage });31 32// Route for browser upload33app.get('/', (req, res) => {34    res.send(`35    <!DOCTYPE html>36    <html lang="en">37    <head>38        <meta charset="UTF-8">39        <meta name="viewport" content="width=device-width, initial-scale=1.0">40        <title>Enhanced File Upload</title>41        <style>42            body {43                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;44                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);45                height: 100vh;46                margin: 0;47                display: flex;48                justify-content: center;49                align-items: center;50            }51            .container {52                background-color: rgba(255, 255, 255, 0.9);53                padding: 2rem;54                border-radius: 10px;55                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);56                text-align: center;57                width: 300px;58            }59            h1 {60                color: #4a5568;61                margin-bottom: 1.5rem;62            }63            form {64                display: flex;65                flex-direction: column;66                align-items: center;67            }68            input[type="file"] {69                display: none;70            }71            .file-label {72                background-color: #4a5568;73                color: white;74                padding: 0.5rem 1rem;75                border-radius: 5px;76                cursor: pointer;77                margin-bottom: 1rem;78                transition: background-color 0.3s ease;79            }80            .file-label:hover {81                background-color: #2d3748;82            }83            #file-name {84                margin-bottom: 1rem;85                word-break: break-all;86            }87            button {88                background-color: #4299e1;89                color: white;90                border: none;91                padding: 0.5rem 1rem;92                border-radius: 5px;93                cursor: pointer;94                transition: background-color 0.3s ease;95            }96            button:hover {97                background-color: #3182ce;98            }99            #upload-progress {100                width: 100%;101                background-color: #e2e8f0;102                border-radius: 5px;103                margin-top: 1rem;104                overflow: hidden;105                display: none;106            }107            #progress-bar {108                width: 0;109                height: 10px;110                background-color: #48bb78;111                transition: width 0.5s ease;112            }113        </style>114    </head>115    <body>116        <div class="container">117            <h1>Upload File</h1>118            <form id="upload-form" action="/upload" method="post" enctype="multipart/form-data">119                <label for="file-upload" class="file-label">Choose File</label>120                <input id="file-upload" type="file" name="file">121                <div id="file-name"></div>122                <button type="submit">Upload</button>123            </form>124            <div id="upload-progress">125                <div id="progress-bar"></div>126            </div>127        </div>128 129        <script>130            const fileUpload = document.getElementById('file-upload');131            const fileName = document.getElementById('file-name');132            const uploadForm = document.getElementById('upload-form');133            const uploadProgress = document.getElementById('upload-progress');134            const progressBar = document.getElementById('progress-bar');135 136            fileUpload.addEventListener('change', (e) => {137                if (e.target.files.length > 0) {138                    fileName.textContent = e.target.files[0].name;139                } else {140                    fileName.textContent = '';141                }142            });143 144            uploadForm.addEventListener('submit', (e) => {145                e.preventDefault();146                if (!fileUpload.files.length) {147                    alert('Please select a file to upload.');148                    return;149                }150 151                const formData = new FormData(uploadForm);152                const xhr = new XMLHttpRequest();153 154                xhr.open('POST', '/upload', true);155 156                xhr.upload.onprogress = (event) => {157                    if (event.lengthComputable) {158                        const percentComplete = (event.loaded / event.total) * 100;159                        uploadProgress.style.display = 'block';160                        progressBar.style.width = percentComplete + '%';161                    }162                };163 164                xhr.onload = function() {165                    if (xhr.status === 200) {166                        alert('Upload complete!');167                        document.body.innerHTML = xhr.responseText;168                    } else {169                        alert('Upload failed. Please try again.');170                    }171                    uploadProgress.style.display = 'none';172                    progressBar.style.width = '0';173                    fileName.textContent = '';174                    uploadForm.reset();175                };176 177                xhr.send(formData);178            });179        </script>180    </body>181    </html>182    `);183});184 185// Handler for browser upload186app.post('/upload', upload.single('file'), (req, res) => {187    if (!req.file) {188        return res.status(400).send('No file uploaded.');189    }190 191    const fileUrl = `https://zhofang-temp-storage.hf.space/${req.file.filename.split('-')[0]}/${req.file.originalname}`;192    res.send(`193    <html>194    <head>195        <title>File Uploaded</title>196        <style>197            body {198                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;199                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);200                height: 100vh;201                margin: 0;202                display: flex;203                justify-content: center;204                align-items: center;205                color: white;206            }207            .container {208                background-color: rgba(255, 255, 255, 0.1);209                padding: 2rem;210                border-radius: 10px;211                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);212                text-align: center;213            }214            a {215                color: #4299e1;216                text-decoration: none;217            }218            a:hover {219                text-decoration: underline;220            }221        </style>222    </head>223    <body>224        <div class="container">225            <h1>File Uploaded Successfully</h1>226            <p>Uploaded 1 file, ${req.file.size} bytes</p>227            <p>Download link: <a href="${fileUrl}">${fileUrl}</a></p>228            <p>wget command: <code>wget ${fileUrl}</code></p>229        </div>230    </body>231    </html>232    `);233 234    // Delete file after 24 hours235    setTimeout(() => {236        fs.unlink(req.file.path, (err) => {237            if (err) console.error(`Error deleting file: ${err}`);238        });239    }, 24 * 60 * 60 * 1000); // 24 hours in milliseconds240});241 242// Route for upload via PUT (like bashupload)243app.put('/:filename', (req, res) => {244    const shortId = generateShortId();245    const filename = req.params.filename;246    const filepath = path.join(uploadDir, `${shortId}-${filename}`);247    const fileStream = fs.createWriteStream(filepath);248 249    req.pipe(fileStream);250 251    fileStream.on('finish', () => {252        const fileUrl = `https://zhofang-temp-storage.hf.space/${shortId}/${filename}`;253        res.send(`Uploaded 1 file, ${req.headers['content-length']} bytes\n\nwget ${fileUrl}\n`);254 255        // Delete file after 24 hours256        setTimeout(() => {257            fs.unlink(filepath, (err) => {258                if (err) console.error(`Error deleting file: ${err}`);259            });260        }, 24 * 60 * 60 * 1000); // 24 hours in milliseconds261    });262 263    fileStream.on('error', (err) => {264        console.error(`Error writing file: ${err}`);265        res.status(500).send('Error uploading file.');266    });267});268 269app.get('/:id/:filename', (req, res) => {270    const filepath = path.join(uploadDir, `${req.params.id}-${req.params.filename}`);271    res.download(filepath, req.params.filename, (err) => {272        if (err) {273            console.error(`Error downloading file: ${err}`);274            res.status(404).send('File not found.');275        }276    });277});278 279app.listen(7860, () => {280    console.log('Server is running on http://localhost:3000');281});