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

How in Koa send generated file

1个答案

1

In Koa, to return server-generated files, we can utilize Koa's middleware mechanism to handle HTTP requests and leverage the Node.js file system (fs) module to read or create files. Below are specific steps and an example:

Step 1: Install necessary npm packages

First, ensure your project has the required packages installed: koa and koa-router. If not installed, install them using npm:

bash
npm install koa koa-router

Step 2: Create the Koa server and set up routes

javascript
const Koa = require('koa'); const Router = require('koa-router'); const fs = require('fs'); const path = require('path'); const app = new Koa(); const router = new Router(); // Set up routes router.get('/download', async (ctx) => { // File path const filePath = path.join(__dirname, 'path/to/your/file.txt'); // Check if file exists if (fs.existsSync(filePath)) { // Set response type to application/octet-stream to indicate it's a file for download ctx.type = 'application/octet-stream'; ctx.body = fs.createReadStream(filePath); ctx.attachment('filename.txt'); // Specify the download filename } else { ctx.status = 404; ctx.body = 'File not found'; } }); // Use route middleware app.use(router.routes()).use(router.allowedMethods()); // Start the server app.listen(3000, () => { console.log('Server is running at http://localhost:3000'); });

Step 3: Test the file download functionality

After starting the server, access http://localhost:3000/download via a browser or tools like curl. The server will then return the file.txt file and prompt the user to download it.

Note

  • Ensure your file path is correct and the server has read permissions for the file.
  • When deploying, prioritize security to avoid directly exposing sensitive or important files.
  • Specify the download filename using ctx.attachment() to enhance user experience.

The above outlines the basic method for returning server-generated files in the Koa framework. For special requirements, such as handling large file downloads or adding download permission verification, additional processing and optimization are necessary.

2024年6月29日 12:07 回复

你的答案