上傳下載在 web 應用中仍是比較常見的,不管是圖片仍是其餘文件等。在 Koa 中,有不少中間件能夠幫助咱們快速的實現功能。html
在前端中上傳文件,咱們都是經過表單來上傳,而上傳的文件,在服務器端並不能像普通參數同樣經過 ctx.request.body
獲取。咱們能夠用 koa-body
中間件來處理文件上傳,它能夠將請求體拼到 ctx.request
中。前端
// app.js const koa = require('koa'); const app = new koa(); const koaBody = require('koa-body'); app.use(koaBody({ multipart: true, formidable: { maxFileSize: 200*1024*1024 // 設置上傳文件大小最大限制,默認2M } })); app.listen(3001, ()=>{ console.log('koa is listening in 3001'); })
使用中間件後,就能夠在 ctx.request.body.files
中獲取上傳的文件內容。須要注意的就是設置 maxFileSize,否則上傳文件一超過默認限制就會報錯。node
接收到文件以後,咱們須要把文件保存到目錄中,返回一個 url 給前端。在 node 中的流程爲git
const reader = fs.createReadStream(file.path)
const writer = fs.createWriteStream('upload/newpath.txt')
reader.pipe(writer)
const router = require('koa-router')(); const fs = require('fs'); router.post('/upload', async (ctx){ const file = ctx.request.body.files.file; // 獲取上傳文件 const reader = fs.createReadStream(file.path); // 建立可讀流 const ext = file.name.split('.').pop(); // 獲取上傳文件擴展名 const upStream = fs.createWriteStream(`upload/${Math.random().toString()}.${ext}`); // 建立可寫流 reader.pipe(upStream); // 可讀流經過管道寫入可寫流 return ctx.body = '上傳成功'; })
該方法適用於上傳圖片、文本文件、壓縮文件等。
koa-send
是一個靜態文件服務的中間件,可用來實現文件下載功能。github
const router = require('koa-router')(); const send = require('koa-send'); router.post('/download/:name', async (ctx){ const name = ctx.params.name; const path = `upload/${name}`; ctx.attachment(path); await send(ctx, path); })
在前端進行下載,有兩個方法: window.open
和表單提交。這裏使用簡單一點的 window.open
。web
<button onclick="handleClick()">當即下載</button> <script> const handleClick = () => { window.open('/download/1.png'); } </script>
這裏 window.open
默認是開啓一個新的窗口,一閃而後關閉,給用戶的體驗並很差,能夠加上第二個參數 window.open('/download/1.png', '_self');
,這樣就會在當前窗口直接下載了。然而這樣是將 url 替換當前的頁面,則會觸發 beforeunload
等頁面事件,若是你的頁面監聽了該事件作一些操做的話,那就有影響了。那麼還可使用一個隱藏的 iframe 窗口來達到一樣的效果。服務器
<button onclick="handleClick()">當即下載</button> <iframe name="myIframe" style="display:none"></iframe> <script> const handleClick = () => { window.open('/download/1.png', 'myIframe'); } </script>
批量下載和單個下載也沒什麼區別嘛,就多執行幾回下載而已嘛。這樣也確實沒什麼問題。若是把這麼多個文件打包成一個壓縮包,再只下載這個壓縮包,是否是體驗起來就好一點了呢。app
archiver
是一個在 Node.js 中能跨平臺實現打包功能的模塊,支持 zip 和 tar 格式。dom
const router = require('koa-router')(); const send = require('koa-send'); const archiver = require('archiver'); router.post('/downloadAll', async (ctx){ // 將要打包的文件列表 const list = [{name: '1.txt'},{name: '2.txt'}]; const zipName = '1.zip'; const zipStream = fs.createWriteStream(zipName); const zip = archiver('zip'); zip.pipe(zipStream); for (let i = 0; i < list.length; i++) { // 添加單個文件到壓縮包 zip.append(fs.createReadStream(list[i].name), { name: list[i].name }) } await zip.finalize(); ctx.attachment(zipName); await send(ctx, zipName); })
若是直接打包整個文件夾,則不須要去遍歷每一個文件 append 到壓縮包裏koa
const zipStream = fs.createWriteStream('1.zip'); const zip = archiver('zip'); zip.pipe(zipStream); // 添加整個文件夾到壓縮包 zip.directory('upload/'); zip.finalize();
注意:打包整個文件夾,生成的壓縮包文件不可存放到該文件夾下,不然會不斷的打包。
當文件名含有中文的時候,可能會出現一些預想不到的狀況。因此上傳時,含有中文的話我會對文件名進行 encodeURI()
編碼進行保存,下載的時候再進行 decodeURI()
解密。
ctx.attachment(decodeURI(path)); await send(ctx, path);
ctx.attachment
將 Content-Disposition 設置爲 「附件」 以指示客戶端提示下載。經過解碼後的文件名做爲下載文件的名字進行下載,這樣下載到本地,顯示的仍是中文名。
然鵝,koa-send
的源碼中,會對文件路徑進行 decodeURIComponent()
解碼:
// koa-send path = decode(path) function decode (path) { try { return decodeURIComponent(path) } catch (err) { return -1 } }
這時解碼後去下載含中文的路徑,而咱們服務器中存放的是編碼後的路徑,天然就找不到對應的文件了。
要想解決這個問題,那麼就別讓它去解碼。不想動 koa-send
源碼的話,可以使用另外一箇中間件 koa-sendfile
代替它。
const router = require('koa-router')(); const sendfile = require('koa-sendfile'); router.post('/download/:name', async (ctx){ const name = ctx.params.name; const path = `upload/${name}`; ctx.attachment(decodeURI(path)); await sendfile(ctx, path); })