使用中间件koa-body上传文件
pnpm add -w koa-body
配置:
这里是项目内配置示例,根据实际框架去配置。
- name: body
options:
multipart: false
jsonLimit: 15mb
formidable:
hashAlgorithm: md5
使用读写流处理文件
这里封装了读写流,并做了处理监听处理,正确返回相应给前端。
import fs from 'fs'
class UploadController extends Controller{
async _upload_(file, filePath) {
return new Promise((resolve, reject) => {
const reader = fs.createReadStream(file.filepath)
reader.on('error', (err) => {
reject(err)
})
const upStream = fs.createWriteStream(filePath)
upStream.on('error', (err) => {
reject(err)
})
upStream.on('finish', () => {
resolve(1)
})
reader.pipe(upStream)
})
}
async upload (ctx) {
const file = ctx.request.files.file;
const ext = file.originalFilename.split('.').pop()
const uploadDir = 'uploads'
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir)
}
const filePath = `${uploadDir}/${Math.random().toString()}.${ext}`;
try {
await this._upload_(file, filePath)
} catch (error) {
return this.send(ctx, `文件上传失败:${error}`)
}
this.send(ctx, `文件上传成功:${file.originalFilename}`)
}
}
export default UploadController