【问题标题】:How to serve static files in node.js after renaming them?重命名后如何在 node.js 中提供静态文件?
【发布时间】:2015-06-10 10:31:24
【问题描述】:

我正在创建一个 node.js 应用程序,用户可以在其中上传文件并稍后下载。 我将文件信息(用户上传的原始文件名,...)存储在 mongodb 文档中,并将该文件命名为与 mongodb 文档 ID 相同。现在我希望我的用户能够使用原始文件名下载该文件。

我想知道的是用户何时在http://myapp.com/mongoDocument_Id 上发送 GET 请求 用户得到一个名为 myOriginalfile.ext 的文件

我知道 node-static 和其他模块,但我无法在发送文件之前重命名它们。

我正在使用 koa.js 框架。

【问题讨论】:

    标签: javascript node.js koa node-static


    【解决方案1】:

    这是一个使用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

    【讨论】:

    • 感谢您的回复,我坚持了 6 个小时。
    • 这也是我在stackoverflow上的第一个问题,所以没想到会有这么快的反应。谢谢
    猜你喜欢
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    • 2013-03-06
    • 2013-10-19
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多