起步
mime 获取文件类型
npm init -y
npm i mime koa
app.js
/*
1. 获取请求资源路径
2. 判断是否存在
3. 获取请求资源类型,设置http 响应头
4. 在http响应头 body 中返回 */
const Koa = require('koa');
const app = new Koa();
const path = require('path');
const fs = require('fs');
const mime = require('mime');
const root = path.resolve('.');
app.use(async (ctx, next) => {
if (ctx.path.startsWith('/static/')) {
let requestPath = ctx.path;
let filePath = path.join(root,requestPath);
if (fs.existsSync(filePath)) {
ctx.response.status == 200
ctx.response.set('Content-Type',mime.getType(requestPath)) // 设置正确的文件类型,否则返回的文件后缀有问题
// 文件需要下载时启用此字段
// ctx.response.set('Content-Disposition','attachment')
ctx.response.body = fs.createReadStream(filePath)
} else {
ctx.response.status == 404
}
}
});
app.listen(3000);
console.log('app started at port 3000...');
网友评论