这是一个使用的简单示例koa-file-server
:
var app = require('koa')();
var route = require('koa-route');
var send = require('koa-file-server')({ root : './static' }).send;
app.use(route.get('/:id', function *(id) {
// TODO: perform lookup from id to filename here.
// We'll use a hardcoded filename as an example.
var filename = 'test.txt';
// Set the looked-up filename as the download name.
this.attachment(filename);
// Send the file.
yield send(this, id);
}));
app.listen(3012);
简而言之:
- 文件存储在
./static
使用 MongoDB id 作为文件名
- 用户请求http://myapp.com/123456
- 您在 MongoDB 中查找该 ID 以找出原始文件名(在上面的示例中,文件名只是硬编码为
test.txt
)
- 该文件使用标头中设置的原始文件名(通过使用)
./static/123456
作为下载提供,这将使浏览器将其存储在本地而不是.Content-Disposition
this.attachment(filename)
test.txt
123456