koa-send文件下載報錯

koa-send文件下載報錯

  1. 當file_path是相對路徑時候,沒問題
const send = require('koa-send');
router.get('/download', async ctx => {
  const send = require('koa-send');
  let file_path = './name.txt';
  
  ctx.attachment(file_path)
  try {
    await send(ctx, file_path)
  } catch (error) {
    ctx.throw(404, '文件不存在')
  }
})
  1. 當file_path爲絕對路徑時候,無法獲取文件
    例如:
router.get('/download', async ctx => {
  const send = require('koa-send');
  const path = require('path');
  
  let file_name = './name.txt';
  // /Users/lee/WebstormProjects/vs_workplace/node/name.txt
  let file_path = path.resolve(__dirname, file_name)
  console.log(file_path);
  
  ctx.attachment(file_path)
  try {
    await send(ctx, file_path)
  } catch (error) {
    ctx.throw(404, '文件不存在')
  }
})

問題在於

https://www.npmjs.com/package/koa-send
path最好不要寫絕對路徑,如果需要文件路徑前綴可以加在root裏
在這裏插入圖片描述

解決方法

router.get('/download', async ctx => {
  const send = require('koa-send');
  let file_name = './name.txt';
  let dir = path.resolve(__dirname);
  
  ctx.attachment(file_name)
  try {
    await send(ctx, file_name, {root: dir})
  } catch (error) {
    ctx.throw(404, '文件不存在')
  }
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章