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');
    });

    .

  • 相关阅读:
    openstack running 2
    openstack running 3
    好东西哟 XD
    Linux 上課用細部調整(转)
    openstack swift install 1
    Spring初识(通过小实例清晰认识Spring)
    Windowphone中如何将项目导出为模板
    WP8点击桌面图标快速恢复应用
    WindowsPhone8中SaveSong方法将音乐文件转存到音乐库中
    Windows Phone 数据绑定之UI Element Binding
  • 原文地址:https://www.cnblogs.com/crazycode2/p/11111848.html
Copyright © 2011-2022 走看看