乐闻世界logo
搜索文章和话题

How to achieves file download with koa?

1个答案

1

Implementing file download functionality in Koa typically involves the following steps:

  1. Handling Requests: First, define a route and its associated handler function to process download requests.
  2. Locating the File: The handler function should identify the path of the file to be downloaded on the server.
  3. Setting Response Headers: To inform the browser that this response is for file download, set appropriate Content-Disposition and Content-Type headers.
  4. Sending the File: Finally, use Koa's response object to send the file content back to the client.

The following is a simple example demonstrating how to implement file download functionality in a Koa application:

js
const Koa = require('koa'); const send = require('koa-send'); const path = require('path'); const app = new Koa(); // Define a route to handle download requests app.use(async (ctx) => { // Assume the filename to be downloaded is fixed const fileName = 'example.txt'; // Set the full path of the file const filePath = path.join(__dirname, 'public', fileName); // Set response headers ctx.set('Content-Disposition', `attachment; filename=${fileName}`); ctx.set('Content-Type', 'application/octet-stream'); // Send the file content as the response await send(ctx, filePath, { root: __dirname }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });

In this example, when the client sends a request to the server, the Koa application uses the koa-send module to send the example.txt file located in the public directory. The Content-Disposition header is set to attachment; filename=example.txt, indicating that the browser should prompt the user to save the file rather than display its contents directly. The Content-Type is set to application/octet-stream, a generic binary file type, informing the browser that this is a binary file.

Please note that the filename in this example is hardcoded, but in practice, you may need to dynamically determine the filename and path based on the request. Additionally, you should handle potential errors such as missing files or insufficient permissions.

2024年6月29日 12:07 回复

你的答案