使用方法
方法一:
使用中間介 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 會自動給你設置好的,如果你設置的不對還可能導致上傳失敗。