使用 koa-body 中間件獲取上傳的文件
koa-body 支持文件、json、form格式的請求體筷登,安裝 koa-body
yarn add koa-body
設(shè)置 koaBody 配置參數(shù),index.js
const Koa = require("koa")
const koaBody = require("koa-body")
const route = require("./router")
const static = require("./static")
const path = require("path")
const app = new Koa()
app.use(
koaBody({
// 支持文件格式
multipart: true,
formidable: {
// 上傳目錄
uploadDir: path.join(__dirname, "static/uploads"),
// 保留文件擴(kuò)展名
keepExtensions: true,
// 修改文件名
onFileBegin: (_, file) => {
file.path = file.path.replace(path.basename(file.path), file.name)
}
}
})
)
app.use(static)
app.use(route.routes(), route.allowedMethods())
app.listen(64723)
接下來完善 /upload 路由班巩,獲取文件逊桦,然后直接返回文件路徑
const path = require("path")
const fs = require("fs")
const route = require("koa-router")()
route.post("/", ctx => {
// 上傳的文件
const files = ctx.request.files
const body = {}
Object.keys(files).forEach(key => {
// 上傳的文件
const file = files[key]
// 查看文件路徑
body[key] = ctx.origin + "/uploads/" + path.basename(file.path)
})
ctx.body = body
})
module.exports = route
使用 Postman 測試
上傳測試
本地磁盤上傳的文件
如果想要查看上傳的文件可以借助koa-static, 在此demo我自己實(shí)現(xiàn)了文件的獲取