koa2实现文件上传服务
使用方法
方法一:
使用中间介 koa-body
方法二:
自己写个借口去接收数据流并保存
方法三:
使用 koa-body 接受文件,自己写个接口做文件保存或处理等操作
这里简单记录方法三
app.js
const Koa = require('koa')
const koaBody = require()
const app = new Koa()
app.use(koaBody({
multipart: reue, // 支持表单上传
formidable: {
maxFileSize: 10 * 1024 * 1024, // 修改文件大小限制,默认位2M
}
}))
api.js
const router = require('koa-router')()
const uploadimg = require('./uploadImg')
router.prefix('/api')
router.post('/uploadImg', async function(ctx, next) {
const imgUrl = await uploadimg(ctx);
if (imgUrl) {
ctx.body = {
data: imgUrl,
message: '文件上传成功',
code: '0',
}
} else {
ctx.body = {
data: imgUrl,
message: '文件上传失败',
code: '1',
}
}
})
module.exports = router
uploadImg.js
const path = require('path');
const fs = require('fs');
const uploadimg = (ctx) => {
console.log(JSON.stringify(ctx.request, null, ' '));
let remotefilePath = null;
if (ctx.request.files['file']) {
// 创建可读流
const reader = fs.createReadStream(ctx.request.files['file']['path']);
let filePath = `${path.resolve(__dirname, '../../publicPath/images')}/${ctx.request.files['file']['name']}`;
remotefilePath = `http://yourServerHostAndPath/images/${ctx.request.files['file']['name']}`;
// 创建可写流
const upStream = fs.createWriteStream(filePath);
// 可读流通过管道写入可写流
reader.pipe(upStream);
}
return remotefilePath;
}
module.exports = uploadimg;
在前端中上传文件
upLoadFile.js
const upload = (file) => { const formData = new FormData(); formData.append('file', file); return fetch({ method: 'post', body: formData, }) }
如上即可,注意的地方,使用 fetch 的话不用刻意去设置 header 的 Content-Type 属性,fetch 会自动给你设置好的,如果你设置的不对还可能导致上传失败。
如果你发现你的学习缺乏动力了,那么你只需要在这里调出这篇博客的一大堆毛病并对作者嗤之以鼻,不断抨击作者直到作者的修改让你满意为止,那么你的动力就自然而来了!

浙公网安备 33010602011771号