javascriptnode.jskoanode-static

How to serve static files in node.js after renaming them?


I am creating a node.js app in which user can upload files and can download later. I am storing file information (original file name that user uploaded, ...) in mongodb document and named that file same as mongodb document id. Now i want my user to be able to download that file with the original file name.

What i want to know is when a user sends a GET request on http://myapp.com/mongoDocument_Id user gets a file named myOriginalfile.ext

I know about node-static and other modules but i can't rename them before sending file.

i am using koa.js framework.


Solution

  • Here's a simple example using 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);
    

    In short: