天天看點

Koa2 檔案上傳下載下傳的示例代碼

檔案上傳

在前端中上傳檔案,我們都是通過表單來上傳,而上傳的檔案,在伺服器端并不能像普通參數一樣通過 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,不然上傳檔案一超過預設限制就會報錯。

接收到檔案之後,我們需要把檔案儲存到目錄中,傳回一個 url 給前端。在 node 中的流程為

  1. 建立可讀流 const reader = fs.createReadStream(file.path)
  2. 建立可寫流 const writer = fs.createWriteStream(‘upload/newpath.txt’)
  3. 可讀流通過管道寫入可寫流 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 是一個靜态檔案服務的中間件,可用來實作檔案下載下傳功能。

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 。

<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>
           

批量下載下傳

批量下載下傳和單個下載下傳也沒什麼差別嘛,就多執行幾次下載下傳而已嘛。這樣也确實沒什麼問題。如果把這麼多個檔案打包成一個壓縮包,再隻下載下傳這個壓縮包,是不是體驗起來就好一點了呢。

檔案打包

archiver 是一個在 Node.js 中能跨平台實作打包功能的子產品,支援 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++) {
 // 添加單個檔案到壓縮包
 zip.append(fs.createReadStream(list[i].name), { name: list[i].name })
 }
 await zip.finalize();
 ctx.attachment(zipName);
 await send(ctx, zipName);
})
           

如果直接打包整個檔案夾,則不需要去周遊每個檔案 append 到壓縮包裡

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);
})
           

繼續閱讀