Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Eggjs实现文件下载 #47

Open
AlexZ33 opened this issue Jun 24, 2021 · 1 comment
Open

Eggjs实现文件下载 #47

AlexZ33 opened this issue Jun 24, 2021 · 1 comment

Comments

@AlexZ33
Copy link
Member

AlexZ33 commented Jun 24, 2021

实现一个网站提交数据后把特定文件压缩打包后浏览器出现下载的功能。

路由

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.get('/', controller.home.index);
  router.get('/download', controller.home.deal);
};

控制器

'use strict';

const path = require('path');
const fs = require('fs');
const jszip = require('jszip');

const Controller = require('egg').Controller;

class HomeController extends Controller {

  /**
   * 首页
   */
  async index() {
    const { ctx } = this;
    ctx.response.type = 'html';
    ctx.body = fs.readFileSync(path.resolve(__dirname, '../view/home.html'));
  }

  /**
   * 处理数据
   */
  async deal() {
    const { ctx } = this;
    // 处理public Path
    const dirPath = path.resolve(__dirname, `../public`);
    if (!fs.existsSync(dirPath)) {
      fs.mkdirSync(dirPath);
    }
    // 打包到egg-static的目录下,也可以是其他目录,有写入权限文件目录即可,后续读取
    const zip = new jszip();
    zip.file('test.txt', 'detail');
    zip.folder('img');
    const content = await zip.generateAsync({ type: 'nodebuffer' });
    const zipPath = `${dirPath}/download.zip`;
    fs.writeFileSync(zipPath, content);
    // 返回
    const stats = fs.statSync(zipPath, {
      encoding: 'utf8',
    });
    ctx.response.set({
      'Content-Type': 'application/octet-stream',
      'Content-Disposition': `attachment; filename=download.zip`,
      'Content-Length': stats.size,
    });
    ctx.body = fs.createReadStream(zipPath);
  }

}

module.exports = HomeController;

资料

eggjs/egg#948

https://www.jianshu.com/p/2689a38cf643

@vistwang
Copy link

vistwang commented Sep 5, 2022

试了不行,前端返回是 json 格式,请问前端部分怎么写呢

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants