如何设置要在 Koa 响应中下载的文件的名称?

How can I set the name for a file that is to be downloaded in a Koa response?

我用node和koa做了一个图片代理(下载一个打不开的图片)。 url /proxy/image 代码是:

...
const PassThrough = require('stream').PassThrough
let query = qs.parse(url.parse(ctx.request.url).query)
let passThroughStream = new PassThrough()
ctx.body = request(query.src).pipe(PassThrough())
...

下载的图片名称是image,但我想重命名图片,怎么办?

如果我正确理解你的问题,你应该可以使用 ctx.attachment() 来完成此操作,它是 ctx.response.attachment() 的别名。所以你可以这样做:

ctx.attachment('my-image.png')

这个attachment方法基本上是以下header的shorthand:

ctx.set('Content-disposition', 'attachment; filename=my-image.png');