zoukankan      html  css  js  c++  java
  • koa 实现下载文件

    文件下载需要使用到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');
    });

    .

  • 相关阅读:
    1093 Count PAT's(25 分)
    1089 Insert or Merge(25 分)
    1088 Rational Arithmetic(20 分)
    1081 Rational Sum(20 分)
    1069 The Black Hole of Numbers(20 分)
    1059 Prime Factors(25 分)
    1050 String Subtraction (20)
    根据生日计算员工年龄
    动态获取当前日期和时间
    对计数结果进行4舍5入
  • 原文地址:https://www.cnblogs.com/crazycode2/p/11111848.html
Copyright © 2011-2022 走看看