diff --git a/js/api.js b/js/api.js index 43418e8..6064248 100644 --- a/js/api.js +++ b/js/api.js @@ -3,15 +3,17 @@ // ============================================================ let token = localStorage.getItem('forumlify-token') || null; +function getAuthHeaders() { + return token ? { 'Authorization': 'Bearer ' + token } : {}; +} + function apiFetch(path, options = {}) { const url = CONFIG.API_BASE_URL + path; const headers = { 'Content-Type': 'application/json', + ...getAuthHeaders(), ...(options.headers || {}) }; - if (token) { - headers['Authorization'] = 'Bearer ' + token; - } return fetch(url, { ...options, headers @@ -80,6 +82,19 @@ const API = { return data; }, + async uploadImage(file) { + const formData = new FormData(); + formData.append('file', file); + const response = await fetch(CONFIG.API_BASE_URL + '/upload', { + method: 'POST', + headers: getAuthHeaders(), + body: formData + }); + const data = await response.json().catch(() => ({ error: '上传响应无效' })); + if (!response.ok || data.error) throw new Error(data.error || '图片上传失败'); + return data; + }, + async updatePost(postId, title, content) { const data = await apiFetch('/posts/' + postId, { method: 'PUT', diff --git a/js/app.js b/js/app.js index 4df0449..6e5b0f1 100644 --- a/js/app.js +++ b/js/app.js @@ -162,7 +162,7 @@ function switchPage(page, param) { if (page === 'new') { document.getElementById('postTitle').value = ''; document.getElementById('postContent').value = ''; - document.getElementById('imagePreview').innerHTML = ''; + clearSelectedImages(); document.getElementById('fileInput').value = ''; document.getElementById('postCaptchaInput').value = ''; refreshCaptcha('post'); @@ -368,24 +368,56 @@ async function openPrivateChat(otherUserId, otherUsername) { // 📸 图片上传(拖拽上传) // ============================================================ +let selectedImageFiles = []; + +function clearSelectedImages() { + selectedImageFiles.forEach(entry => URL.revokeObjectURL(entry.previewUrl)); + selectedImageFiles = []; + const preview = document.getElementById('imagePreview'); + if (preview) preview.innerHTML = ''; +} + function handleImageFiles(files) { const preview = document.getElementById('imagePreview'); if (!preview) return; - for (let file of files) { - if (!file.type.startsWith('image/')) continue; + + for (const file of files) { + if (selectedImageFiles.length >= 6) { + alert('每篇帖子最多上传 6 张图片'); + break; + } + if (!['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(file.type)) { + alert('图片 ' + file.name + ' 格式不支持'); + continue; + } if (file.size > 5 * 1024 * 1024) { alert('图片 ' + file.name + ' 超过 5MB,请压缩后上传'); continue; } - const reader = new FileReader(); - reader.onload = function(e) { - const img = document.createElement('img'); - img.src = e.target.result; - img.style.cssText = 'width:80px;height:80px;object-fit:cover;border-radius:4px;border:1px solid var(--border);'; - preview.appendChild(img); - }; - reader.readAsDataURL(file); + + const entry = { file, previewUrl: URL.createObjectURL(file) }; + selectedImageFiles.push(entry); + + const wrapper = document.createElement('div'); + wrapper.style.cssText = 'position:relative;width:80px;height:80px;'; + const img = document.createElement('img'); + img.src = entry.previewUrl; + img.alt = file.name; + img.style.cssText = 'width:80px;height:80px;object-fit:cover;border-radius:4px;border:1px solid var(--border);'; + const remove = document.createElement('button'); + remove.type = 'button'; + remove.textContent = '×'; + remove.setAttribute('aria-label', '移除 ' + file.name); + remove.style.cssText = 'position:absolute;top:2px;right:2px;width:22px;height:22px;border:0;border-radius:50%;background:rgba(0,0,0,.7);color:#fff;cursor:pointer;'; + remove.addEventListener('click', () => { + selectedImageFiles = selectedImageFiles.filter(item => item !== entry); + URL.revokeObjectURL(entry.previewUrl); + wrapper.remove(); + }); + wrapper.append(img, remove); + preview.appendChild(wrapper); } + const fileInput = document.getElementById('fileInput'); if (fileInput) fileInput.value = ''; } @@ -1243,19 +1275,27 @@ async function init() { const captchaAnswer = parseInt(document.getElementById('postCaptchaInput').dataset.answer); if (!content) { alert('请填写内容'); return; } if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('post'); return; } - const images = []; - document.querySelectorAll('#imagePreview img').forEach(img => { - images.push(img.src); - }); + const submitButton = document.getElementById('postSubmit'); + submitButton.disabled = true; + submitButton.textContent = selectedImageFiles.length ? '上传图片中...' : '发布中...'; try { + const images = []; + for (const entry of selectedImageFiles) { + const uploaded = await API.uploadImage(entry.file); + images.push(uploaded.url); + } await API.createPost(title, content, images); alert('发布成功!'); + clearSelectedImages(); switchPage('feed'); renderFeed(); renderStats(); } catch (err) { alert('发布失败:' + err.message); + } finally { + submitButton.disabled = false; + submitButton.textContent = '发布帖子'; } }); diff --git a/server.js b/server.js index 1e8628d..a3f0608 100644 --- a/server.js +++ b/server.js @@ -791,12 +791,18 @@ app.post('/api/posts', auth, async (req, res) => { return res.status(400).json({ error: '帖子字段长度或图片数量无效' }); } + const imagePaths = images || []; + const uploadPathPattern = /^\/uploads\/[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.(?:jpg|png|gif|webp)$/i; + if (!Array.isArray(imagePaths) || imagePaths.length > 6 || imagePaths.some(image => !uploadPathPattern.test(image))) { + return res.status(400).json({ error: '图片地址无效或数量超过限制' }); + } + try { const r = await pool.query( `INSERT INTO posts (user_id, title, content, images) VALUES ($1, $2, $3, $4) RETURNING *`, - [req.user.id, title?.trim() || '无标题', content.trim(), images || []] + [req.user.id, title?.trim() || '无标题', content.trim(), imagePaths] ); res.json(r.rows[0]); } catch (err) { @@ -1196,29 +1202,51 @@ app.get('/api/event-logs', auth, admin, async (req, res) => { // 图片上传 // ============================================================ -const storage = multer.diskStorage({ - destination: (req, file, cb) => cb(null, 'uploads/'), - filename: (req, file, cb) => { - const ext = path.extname(file.originalname); - const name = Date.now() + '-' + Math.round(Math.random() * 10000) + ext; - cb(null, name); - } -}); - const upload = multer({ - storage, + storage: multer.memoryStorage(), limits: { fileSize: 5 * 1024 * 1024 }, - fileFilter: (req, file, cb) => { - const allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']; - cb(null, allowed.includes(file.mimetype)); - } }); -app.post('/api/upload', auth, upload.single('file'), (req, res) => { +function detectImageType(buffer) { + if (!buffer || buffer.length < 12) return null; + if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) { + return { extension: '.jpg', mime: 'image/jpeg' }; + } + if (buffer.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) { + return { extension: '.png', mime: 'image/png' }; + } + const header = buffer.subarray(0, 6).toString('ascii'); + if (header === 'GIF87a' || header === 'GIF89a') { + return { extension: '.gif', mime: 'image/gif' }; + } + if (buffer.subarray(0, 4).toString('ascii') === 'RIFF' && buffer.subarray(8, 12).toString('ascii') === 'WEBP') { + return { extension: '.webp', mime: 'image/webp' }; + } + return null; +} + +app.post('/api/upload', auth, upload.single('file'), async (req, res, next) => { if (!req.file) { return res.status(400).json({ error: '请选择图片' }); } - res.json({ url: '/uploads/' + req.file.filename }); + + const imageType = detectImageType(req.file.buffer); + if (!imageType) { + return res.status(400).json({ error: '仅支持有效的 JPG、PNG、GIF 或 WebP 图片' }); + } + + const filename = crypto.randomUUID() + imageType.extension; + try { + await fs.promises.writeFile(path.join(__dirname, 'uploads', filename), req.file.buffer, { flag: 'wx' }); + res.setHeader('X-Content-Type-Options', 'nosniff'); + return res.status(201).json({ + url: '/uploads/' + filename, + mime: imageType.mime, + size: req.file.size, + }); + } catch (error) { + return next(error); + } }); // ============================================================