koa-send文件下载报错
- 当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, '文件不存在')
}
})
- 当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, '文件不存在')
}
})