koa 实现下载文件

本文介绍了如何在Node.js的Koa框架中利用koa-send中间件实现文件下载功能。通过修改app.js代码并配合静态文件服务,可以创建一个下载页面供用户下载文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件下载需要使用到koa-send这个插件,该插件是一个静态文件服务的中间件,它可以用来实现文件下载的功能。

1.下载页面

static/download.html

<!DOCTYPE html>
<html>

<head>
  <meta charset=utf-8>
  <title>文件下载演示</title>
</head>

<body>

  <div>
    <button onclick="fileLoad()">文件下载</button>
    <iframe name="iframeId" style="display:none"></iframe>
  </div>
  <script type="text/javascript">
    function fileLoad() {
      window.open('/static/upload/pro_03.jpg', 'iframeId');
    }
  </script>
</body>

</html>

2.app.js 所有的代码改成如下:

// 引入模块
const Koa = require('koa');
const fs = require('fs');
const path = require('path');
const router = require('koa-router')();
const koaBody = require('koa-body');
const static = require('koa-static');
const send = require('koa-send');

// 实例化
const app = new Koa();

app.use(koaBody());

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

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

// 配置静态资源路径
app.use(static(path.join(__dirname)));

// 启动路由
app.use(router.routes()).use(router.allowedMethods());

// 监听端口号
app.listen(3001, () => {
  console.log('server is listen in 3001');
});

.

转载于:https://www.cnblogs.com/crazycode2/p/11111848.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值