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串,不是一个文件,请问该如何解除
丢到public目录即可。不用自己写。
@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');
});
koa 提供了 attachment 方法

可以进一步简化:
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');
});
谢谢大家 问题我找到了 我是ajax发请求去下载文件
....
这个也可以做 我现在是异步问题不知道怎么处理
我可以写成一个example放到eggs/example么?
欢迎
https://github.com/eggjs/examples/pull/28 这个咯, 有问题请告诉我。
Most helpful comment
https://github.com/eggjs/examples/pull/28 这个咯, 有问题请告诉我。