Skip to content
New issue

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 #3

Open
programmer-yang opened this issue Nov 7, 2017 · 1 comment
Open

关于Koa #3

programmer-yang opened this issue Nov 7, 2017 · 1 comment
Labels

Comments

@programmer-yang
Copy link
Owner

记录自己在使用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());
@programmer-yang
Copy link
Owner Author

时隔4年更新一波

现在koa写文件上传更方便了,官方插件koa-body就支持

const koaBody = require("koa-body");

app.use(koaBody({
  multipart: true,
  formidable: {
    uploadDir: path.join(__dirname, 'public'),
    keepExtensions: true,
  }
}))

配合koa-static就可以直接实现一个mini的文件上传了

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)}` }
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant