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

595 views Asked by At

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.

1

There are 1 answers

2
robertklep On BEST ANSWER

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:

  • the files are stored in ./static using the MongoDB id as their filename
  • a user requests http://myapp.com/123456
  • you look up that ID in MongoDB to find out the original filename (in the example above, the filename is just hardcoded to test.txt)
  • the file ./static/123456 is offered as a download using the original filename set in the Content-Disposition header (by using this.attachment(filename)), which will make the browser store it locally as test.txt instead of 123456.