We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
记录自己在使用koa的时候遇到的问题和解决办法
工作中有个需求需要自己实现一个文件上传来测试React的一个图片上传组件
参考资料: 官方关于文件上传的demo 官方关于跨域的解决方案
实现方式就是在官方文件上传的基础上修改几行代码实现跨域文件上传
官方demo中文件上传后是直接跳转了,这里我修改了返回json格式的响应内容,可把文件名放进去实现前端暂时上传成功的图片
// const stream = fs.createWriteStream(os.tmpdir(), Math.random().toString())); const stream = fs.createWriteStream(path.join(`${__dirname}/public/tmp/`, file.name)); reader.pipe(stream); console.log('uploading %s -> %s', file.name, stream.path); // ctx.redirect('/'); ctx.response.body = { code: 0, filePath: `public/tmp/${file.name}` };
添加跨域的支持
添加在顶部即可
const cors = require('@koa/cors'); app.use(cors());
The text was updated successfully, but these errors were encountered:
时隔4年更新一波
现在koa写文件上传更方便了,官方插件koa-body就支持
koa-body
const koaBody = require("koa-body"); app.use(koaBody({ multipart: true, formidable: { uploadDir: path.join(__dirname, 'public'), keepExtensions: true, } }))
配合koa-static就可以直接实现一个mini的文件上传了
koa-static
const koaStatic = require("koa-static"); app.use(koaStatic(path.join(__dirname, 'public'))); router.post('/upload', ctx => { ctx.body = { url: `${ctx.origin}/${path.basename(ctx.request.files.file.path)}` } })
Sorry, something went wrong.
No branches or pull requests
文件上传 跨域
参考资料:
官方关于文件上传的demo
官方关于跨域的解决方案
实现方式就是在官方文件上传的基础上修改几行代码实现跨域文件上传
添加跨域的支持
The text was updated successfully, but these errors were encountered: