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

文件下载如何设置? #965

Closed
GeneralFy opened this issue May 27, 2017 · 9 comments
Closed

文件下载如何设置? #965

GeneralFy opened this issue May 27, 2017 · 9 comments

Comments

@GeneralFy
Copy link

        const buffer = Buffer.from(JSON.stringify(writeJson),'utf8');
        ctx.res.statusCode = 200;
        ctx.set('content-type','application/octet-stream');
        ctx.set('content-disposition','attachment; filename=test.json');
        ctx.body = buffer;

代码是这样写的,但是浏览器响应的是json串,不是一个文件,请问该如何解除

@ngot
Copy link
Member

ngot commented May 27, 2017

丢到public目录即可。不用自己写。

@atian25
Copy link
Member

atian25 commented May 27, 2017

@GeneralFy 你是不是浏览器的问题? 我无法复现,是可以直接下载的,chrome。

另外你的代码可以精简下:

  app.get('/download', function* () {
    const ctx = this;
    ctx.status = 200;
    ctx.body = { a: 'b' };
    ctx.set('content-type', 'application/octet-stream');
    ctx.set('content-disposition', 'attachment; filename=test.json');
  });

@dead-horse
Copy link
Member

koa 提供了 attachment 方法

image

可以进一步简化:

app.get('/download', function* () {
    const ctx = this;
    ctx.status = 200;
    ctx.body = { a: 'b' };
    ctx.set('content-type', 'application/octet-stream');
    ctx.attachment('test.json');
  });

@GeneralFy
Copy link
Author

谢谢大家 问题我找到了 我是ajax发请求去下载文件

@atian25
Copy link
Member

atian25 commented May 27, 2017

....

@GeneralFy
Copy link
Author

这个也可以做 我现在是异步问题不知道怎么处理

@monkindey
Copy link
Contributor

我可以写成一个example放到eggs/example么?

@atian25
Copy link
Member

atian25 commented May 27, 2017

欢迎

@monkindey
Copy link
Contributor

eggjs/examples#28 这个咯, 有问题请告诉我。

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

No branches or pull requests

5 participants