文件下載需要使用到koa-send這個插件,該插件是一個靜態文件服務的中間件,它可以用來實現文件下載的功能。
1.下載頁面
static/download.html
<!DOCTYPE html> <html> <head> <meta charset=utf-8> <title>文件下載演示</title> </head> <body> <div> <button onclick="fileLoad()">文件下載</button> <iframe name="iframeId" style="display:none"></iframe> </div> <script type="text/javascript"> function fileLoad() { window.open('/static/upload/pro_03.jpg', 'iframeId'); } </script> </body> </html>
2.app.js 所有的代碼改成如下:
// 引入模塊 const Koa = require('koa'); const fs = require('fs'); const path = require('path'); const router = require('koa-router')(); const koaBody = require('koa-body'); const static = require('koa-static'); const send = require('koa-send'); // 實例化 const app = new Koa(); app.use(koaBody()); router.get('/', (ctx) => { // 設置頭類型, 如果不設置,會直接下載該頁面 ctx.type = 'html'; // 讀取文件 const pathUrl = path.join(__dirname, '/static/download.html'); ctx.body = fs.createReadStream(pathUrl); }); router.get('/fileload/:name', async (ctx) => { const name = ctx.params.name; const path = `static/upload/${name}`; ctx.attachment(path); await send(ctx, path); }); // 配置靜態資源路徑 app.use(static(path.join(__dirname))); // 啟動路由 app.use(router.routes()).use(router.allowedMethods()); // 監聽端口號 app.listen(3001, () => { console.log('server is listen in 3001'); });
.