關於koa-body上傳文件的基本流程記錄

一、前端

upload(){
    const file = document.querySelector("#file");
    const fd = new FormData(); // 需要創建一個表單對象
    fd.append("f",file.files[0])
    axios({
      method:'post',
      url: '/api/upload',
      data: fd
    })
}

二、後端

app.use(koaBody({
  multipart: true
})

...

router.post("/api/upload", async (ctx, next) => {
  const file = ctx.request.body.files.f;
  // 獲取上傳文件,f是表單名稱即name,是自己定義的
  const reader = fs.createReadStream(file.path);
  const filename = (new Date()).valueOf() + file.name;
  let filePath = path.join(__dirname, 'upload/') + `/${filename}`;
  // 創建可寫流
  const upStream = fs.createWriteStream(filePath);
  // 可讀流通過管道寫入可寫流
  reader.pipe(upStream);
  ctx.body = "success";
})

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章