首頁  >  文章  >  web前端  >  koa2實作檔案上傳下載步驟詳解

koa2實作檔案上傳下載步驟詳解

php中世界最好的语言
php中世界最好的语言原創
2018-04-27 17:22:301456瀏覽

這次帶給大家koa2實作檔案上傳下載步驟詳解,koa2實作檔案上傳下載的注意事項有哪些,下面就是實戰案例,一起來看一下。

前言

上傳下載在 web 應用程式中還是比較常見的,無論是圖片或其他檔案等。在 Koa 中,有許多中間件可以幫助我們快速的實作功能。

文件上傳

在前端上傳文件,我們都是透過表單上傳,而上傳的文件,在伺服器端並不能像普通參數一樣透過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);
})

我相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

vue axios請求攔截實作想法(附程式碼)

#vue2實作購物車與位址選配步驟詳解

vue.js樹形控制項使用詳解

#

以上是koa2實作檔案上傳下載步驟詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn