前言
代码地址
开发前需要掌握的一些库
koa:用来起一个web服务器
koa2-cors: 解决跨域问题
@koa/router: koa的路由处理
koa-body: koa参数的获取
koa-static: 静态内容
@koa/multer multer:图片上传的插件
代码结构
实现代码
1.第一步:用koa+koa-router搭建一个简单的web服务
//main.js const koa = require('koa') // 引入koa const router = require('koa-router') // 引入koa-router const koabody = require('koa-body') router.get('/', async (ctx) => { ctx.type = 'html' ctx.body = '<h1>hello world!</h1>' }) app.use(router.routes()) .use(router.allowedmethods()) .use(koabody()) // 启动服务监听本地3000端口 app.listen(3000, () => { console.log('应用已经启动,http://localhost:3000') })
现在我们就可以打开http://localhost:3000看到 hello world
2.接着我们新建一个upload文件夹,且在代码中加入静态内容的的代码
//mian.js 新增代码 const serve = require('koa-static') const path = require('path') app.use(serve(path.join(__dirname, './upload')))
此时假如你在upload文件夹下新增一张照片便可通过http://localhost:3000/***.png 查看到了。(***:你自己新增的照片名称加后缀)
3.此时新增一个index.html文件,且加入以下代码
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>document</title> </head> <body> <input type="file" class="file" name="avatar"> <button onclick="send()">上传</button> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script> let formdata = new formdata() document.queryselector('.file').addeventlistener('change', function(e) { let files = e.target.files console.log(files) if (!files.length) return formdata.append('file', files[0], files[0].name) }) function send(){ axios.post('http://localhost:3000/upload',formdata,{ headers:{ "content-type":"multipart/form-data" } }) } </script> </body> </html>
选择图片且上传会发现存在跨域问题,那么发现问题解决问题直接上代码:
//mian.js新增代码 const cors = require('koa2-cors') app.use(cors())//注意这个配置要在router前使用不然不生效
解决完跨域后,选择图片且上传.咦~404好吧没有新增对应的router,走起:
router.post('/upload', async (ctx) => { ctx.body = 'ok' })
此时咱们已经拿到传过来的数据啦,重头戏来了:@koa/multer使用
const multer = require('@koa/multer') const storage = multer.diskstorage({ destination: function (req, file, cb) { cb(null, './upload') }, filename: function (req, file, cb) { const fileformat = (file.originalname).split('.') cb(null, date.now() + '.' + fileformat[fileformat.length - 1]) } }) const upload = multer({ storage })
配置好后修改/upload
router.post('/upload', upload.single('file'), async (ctx) => { console.log('ctx.request.body', ctx.request.body) ctx.body = 'done' })
note:需要注意的是upload.single(‘file’),中的file需要和上方的index.html中的formdata字段一致 此时就可以愉快的上传啦~~~
到此这篇关于利用node+koa+axios实现图片上传和回显功能的文章就介绍到这了,更多相关node koa axios图片上传回显内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
声明:如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。