下载文件和访问HTML页面示例

PS:在项目的根目录新增static文件夹,static文件夹中包含load.html页面和模板文件.xlsx。

const koa = require('koa');
const Router = require('koa-router');
const app = new koa();
const port = 4444; // 端口号
const router = new Router();
const koaBody = require('koa-body')
const path = require('path');
const fs = require('fs');
const static = require('koa-static');
const send = require('koa-send');

// 浏览器访问页面load.html
router.get('/hm', (ctx) => {
    ctx.type = 'html'; // 设置头类型, 如果不设置,会直接下载该页面
    const pathUrl = path.join(__dirname, '/static/load.html'); // 读取文件
    ctx.body = fs.createReadStream(pathUrl);
});

// 下载问价
router.get('/fileload/:name', async (ctx) => {
    const name = ctx.params.name;
    const path = `static/${name}`;
    ctx.attachment(path);
    await send(ctx, path);
});

app.use(router.routes());
app.use(router.allowedMethods());
app.use(static(path.join(__dirname)));
app.listen(port, () => {
    console.log('server listen =' + port);
})
访问页面:http://localhost:4444/hm  
下载模板:http://localhost:4444/fileload/模板文件.xlsx
======
参考文件:http://t.zoukankan.com/tugenhua0707-p-10828869.html
posted on 2022-10-25 13:14  羽丫头不乖  阅读(267)  评论(0编辑  收藏  举报