Koa2 之文件上傳下載
上傳下載在 web 應(yīng)用中還是比較常見(jiàn)的,無(wú)論是圖片還是其他文件等。在 Koa 中,有很多中間件可以幫助我們快速的實(shí)現(xiàn)功能。
文件上傳
在前端中上傳文件,我們都是通過(guò)表單來(lái)上傳,而上傳的文件,在服務(wù)器端并不能像普通參數(shù)一樣通過(guò) ctx.request.body 獲取。我們可以用 koa-body 中間件來(lái)處理文件上傳,它可以將請(qǐng)求體拼到 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 // 設(shè)置上傳文件大小***限制,默認(rèn)2M
- }
- }));
- app.listen(3001, ()=>{
- console.log('koa is listening in 3001');
- })
使用中間件后,就可以在 ctx.request.body.files 中獲取上傳的文件內(nèi)容。需要注意的就是設(shè)置 maxFileSize,不然上傳文件一超過(guò)默認(rèn)限制就會(huì)報(bào)錯(cuò)。
接收到文件之后,我們需要把文件保存到目錄中,返回一個(gè) url 給前端。在 node 中的流程為
- 創(chuàng)建可讀流 const reader = fs.createReadStream(file.path)
- 創(chuàng)建可寫(xiě)流 const writer = fs.createWriteStream('upload/newpath.txt')
- 可讀流通過(guò)管道寫(xiě)入可寫(xiě)流 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); // 創(chuàng)建可讀流
- const ext = file.name.split('.').pop(); // 獲取上傳文件擴(kuò)展名
- const upStream = fs.createWriteStream(`upload/${Math.random().toString()}.${ext}`); // 創(chuàng)建可寫(xiě)流
- reader.pipe(upStream); // 可讀流通過(guò)管道寫(xiě)入可寫(xiě)流
- return ctx.body = '上傳成功';
- })
該方法適用于上傳圖片、文本文件、壓縮文件等。
文件下載
koa-send 是一個(gè)靜態(tài)文件服務(wù)的中間件,可用來(lái)實(shí)現(xiàn)文件下載功能。
- 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);
- })
在前端進(jìn)行下載,有兩個(gè)方法: window.open 和表單提交。這里使用簡(jiǎn)單一點(diǎn)的 window.open。
- <button onclick="handleClick()">立即下載</button>
- <script>
- const handleClick = () => {
- window.open('/download/1.png');
- }
- </script>
這里 window.open 默認(rèn)是開(kāi)啟一個(gè)新的窗口,一閃然后關(guān)閉,給用戶的體驗(yàn)并不好,可以加上第二個(gè)參數(shù) window.open('/download/1.png', '_self');,這樣就會(huì)在當(dāng)前窗口直接下載了。然而這樣是將 url 替換當(dāng)前的頁(yè)面,則會(huì)觸發(fā) beforeunload 等頁(yè)面事件,如果你的頁(yè)面監(jiān)聽(tīng)了該事件做一些操作的話,那就有影響了。那么還可以使用一個(gè)隱藏的 iframe 窗口來(lái)達(dá)到同樣的效果。
- <button onclick="handleClick()">立即下載</button>
- <iframe name="myIframe" style="display:none"></iframe>
- <script>
- const handleClick = () => {
- window.open('/download/1.png', 'myIframe');
- }
- </script>
批量下載
批量下載和單個(gè)下載也沒(méi)什么區(qū)別嘛,就多執(zhí)行幾次下載而已嘛。這樣也確實(shí)沒(méi)什么問(wèn)題。如果把這么多個(gè)文件打包成一個(gè)壓縮包,再只下載這個(gè)壓縮包,是不是體驗(yàn)起來(lái)就好一點(diǎn)了呢。
文件打包
archiver 是一個(gè)在 Node.js 中能跨平臺(tái)實(shí)現(xiàn)打包功能的模塊,支持 zip 和 tar 格式。
- 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++) {
- // 添加單個(gè)文件到壓縮包
- zip.append(fs.createReadStream(list[i].name), { name: list[i].name })
- }
- await zip.finalize();
- ctx.attachment(zipName);
- await send(ctx, zipName);
- })
如果直接打包整個(gè)文件夾,則不需要去遍歷每個(gè)文件 append 到壓縮包里
- const zipStream = fs.createWriteStream('1.zip');
- const zip = archiver('zip');
- zip.pipe(zipStream);
- // 添加整個(gè)文件夾到壓縮包
- zip.directory('upload/');
- zip.finalize();
注意:打包整個(gè)文件夾,生成的壓縮包文件不可存放到該文件夾下,否則會(huì)不斷的打包。
中文編碼問(wèn)題
當(dāng)文件名含有中文的時(shí)候,可能會(huì)出現(xiàn)一些預(yù)想不到的情況。所以上傳時(shí),含有中文的話我會(huì)對(duì)文件名進(jìn)行 encodeURI() 編碼進(jìn)行保存,下載的時(shí)候再進(jìn)行 decodeURI() 解密。
- ctx.attachment(decodeURI(path));
- await send(ctx, path);
ctx.attachment 將 Content-Disposition 設(shè)置為 “附件” 以指示客戶端提示下載。通過(guò)解碼后的文件名作為下載文件的名字進(jìn)行下載,這樣下載到本地,顯示的還是中文名。
然鵝,koa-send 的源碼中,會(huì)對(duì)文件路徑進(jìn)行 decodeURIComponent() 解碼:
- // koa-send
- path = decode(path)
- function decode (path) {
- try {
- return decodeURIComponent(path)
- } catch (err) {
- return -1
- }
- }
這時(shí)解碼后去下載含中文的路徑,而我們服務(wù)器中存放的是編碼后的路徑,自然就找不到對(duì)應(yīng)的文件了。
要想解決這個(gè)問(wèn)題,那么就別讓它去解碼。不想動(dòng) koa-send 源碼的話,可使用另一個(gè)中間件 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);
- })
【本文為51CTO專欄作者“林鑫”的原創(chuàng)稿件,轉(zhuǎn)載請(qǐng)通過(guò)微信公眾號(hào)聯(lián)系作者獲取授權(quán)】