import Router from 'koa-router' import { default as fs, promises as pfs } from 'fs' import path from 'path' import {koaBody} from 'koa-body' const router = new Router({prefix: '/upload'}) router.get('/', async ctx => { try { // 读取 HTML 文件的内容 const htmlContent = await pfs.readFile(path.join(import.meta.dirname, 'upload.html'), 'utf8'); // 将 HTML 文件内容作为响应发送 ctx.type = 'text/html'; ctx.body = htmlContent; } catch (error) { console.error('Error reading HTML file:', error); ctx.status = 500; ctx.body = 'Internal Server Error'; } }) // 接收上传文件的路由,每次只能上传一个 router.post('/single', koaBody({ multipart: true, formidable: { uploadDir: path.join(import.meta.dirname, 'upload', 'image'), keepExtensions: true, // 保持文件扩展名 maxFileSize: 10 * 1024 * 1024 // 10 MB } }), async (ctx, next) => { try { const file = ctx.request.files.file; // 获取上传的文件对象 // 获取文件类型 const fileType = file.type.split('/')[1]; // 检查文件类型,这里假设只允许上传 jpg 文件 if (fileType !== 'jpg') { ctx.status = 415; // 不支持的媒体类型 ctx.body = 'Unsupported file type (only .jpg allowed)'; return; } ctx.status = 200; ctx.body = 'File uploaded successfully'; } catch (error) { console.error('Error uploading file:', error); ctx.status = 500; ctx.body = 'Internal Server Error'; } }); export default router