Secure image uploads and post publishing

This commit is contained in:
Arun committed 2026-08-11 09:38:33 +00:00
1 parent 145f13fee5
commit 5605ded575
3 files changed
+112 -30

No files matched your search

+13
View File
@@ -80,6 +80,19 @@ const API = {
return data; 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: token ? { 'Authorization': 'Bearer ' + token } : {},
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) { async updatePost(postId, title, content) {
const data = await apiFetch('/posts/' + postId, { const data = await apiFetch('/posts/' + postId, {
method: 'PUT', method: 'PUT',
+53 -13
View File
@@ -162,7 +162,7 @@ function switchPage(page, param) {
if (page === 'new') { if (page === 'new') {
document.getElementById('postTitle').value = ''; document.getElementById('postTitle').value = '';
document.getElementById('postContent').value = ''; document.getElementById('postContent').value = '';
document.getElementById('imagePreview').innerHTML = ''; clearSelectedImages();
document.getElementById('fileInput').value = ''; document.getElementById('fileInput').value = '';
document.getElementById('postCaptchaInput').value = ''; document.getElementById('postCaptchaInput').value = '';
refreshCaptcha('post'); 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) { function handleImageFiles(files) {
const preview = document.getElementById('imagePreview'); const preview = document.getElementById('imagePreview');
if (!preview) return; 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) { if (file.size > 5 * 1024 * 1024) {
alert('图片 ' + file.name + ' 超过 5MB,请压缩后上传'); alert('图片 ' + file.name + ' 超过 5MB,请压缩后上传');
continue; continue;
} }
const reader = new FileReader();
reader.onload = function(e) { 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'); const img = document.createElement('img');
img.src = e.target.result; 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);'; img.style.cssText = 'width:80px;height:80px;object-fit:cover;border-radius:4px;border:1px solid var(--border);';
preview.appendChild(img); const remove = document.createElement('button');
}; remove.type = 'button';
reader.readAsDataURL(file); 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'); const fileInput = document.getElementById('fileInput');
if (fileInput) fileInput.value = ''; if (fileInput) fileInput.value = '';
} }
@@ -1236,19 +1268,27 @@ async function init() {
const captchaAnswer = parseInt(document.getElementById('postCaptchaInput').dataset.answer); const captchaAnswer = parseInt(document.getElementById('postCaptchaInput').dataset.answer);
if (!content) { alert('请填写内容'); return; } if (!content) { alert('请填写内容'); return; }
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('post'); return; } if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('post'); return; }
const images = []; const submitButton = document.getElementById('postSubmit');
document.querySelectorAll('#imagePreview img').forEach(img => { submitButton.disabled = true;
images.push(img.src); submitButton.textContent = selectedImageFiles.length ? '上传图片中...' : '发布中...';
});
try { 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); await API.createPost(title, content, images);
API.logEvent('create_post').catch(() => {}); API.logEvent('create_post').catch(() => {});
alert('发布成功!'); alert('发布成功!');
clearSelectedImages();
switchPage('feed'); switchPage('feed');
renderFeed(); renderFeed();
renderStats(); renderStats();
} catch (err) { } catch (err) {
alert('发布失败:' + err.message); alert('发布失败:' + err.message);
} finally {
submitButton.disabled = false;
submitButton.textContent = '发布帖子';
} }
}); });
+46 -17
View File
@@ -13,6 +13,7 @@ const { Pool } = require('pg');
const multer = require('multer'); const multer = require('multer');
const path = require('path'); const path = require('path');
const fs = require('fs'); const fs = require('fs');
const crypto = require('crypto');
const app = express(); const app = express();
@@ -564,12 +565,18 @@ app.post('/api/posts', auth, async (req, res) => {
return res.status(400).json({ error: '请填写内容' }); 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 { try {
const r = await pool.query( const r = await pool.query(
`INSERT INTO posts (user_id, title, content, images) `INSERT INTO posts (user_id, title, content, images)
VALUES ($1, $2, $3, $4) VALUES ($1, $2, $3, $4)
RETURNING *`, RETURNING *`,
[req.user.id, title || '无标题', content, images || []] [req.user.id, title || '无标题', content, imagePaths]
); );
res.json(r.rows[0]); res.json(r.rows[0]);
} catch (err) { } catch (err) {
@@ -985,29 +992,51 @@ app.post('/api/event-logs', auth, 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({ const upload = multer({
storage, storage: multer.memoryStorage(),
limits: { fileSize: 5 * 1024 * 1024 }, 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) { if (!req.file) {
return res.status(400).json({ error: '请选择图片' }); 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);
}
}); });
// ============================================================ // ============================================================