koa --- 使用koa-multer上传文件+elementUI
生活随笔
收集整理的這篇文章主要介紹了
koa --- 使用koa-multer上传文件+elementUI
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
核心代碼
const upload = require('koa-multer') ({dest: './public/images'}); router.post('/upload', upload.single('file'), ctx=>{console.log('file', ctx.req.file);console.log('body', ctx.req.body);ctx.body = '上傳成功'; })目錄結構如下
基本思路
- 1.通過瀏覽器訪問url: http://localhost:3000/upload
- 2.服務器(koa)監聽到對應的路由,調用路由處理函數
- 3.使用nunjucks模板引擎進行渲染,并返回給瀏覽器
- 4.瀏覽器渲染完畢后顯示出來.
- 5.點擊上傳文件->上傳
- 6.服務端監聽到上傳的POST請求,進行相應的處理并將處理結果返回給前端
總體代碼
- /upload.js
- /upload.html
Element-ui組件(前端)文件上傳
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script><script src="https://unpkg.com/element-ui/lib/index.js"></script><link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"><style>.avatar-uploader .el-upload{border: 1px dashed #d9d9d9;border-radius: 6px;cursor: pointer;position: relative;}.avatar-uploader-icon{font-size: 28px;color: #8c939d;width: 178px;height: 178px;line-height: 178px;text-align: center;}.avatar{width: 178px;height: 178px;display: block;}</style><title>文件上傳</title> </head> <body><div id="app"><!-- ajax方式上傳--><el-uploadclass="avatar-uploader"action="http://localhost:3000/users/upload":show-file-list="false":on-success="handleAvatarSuccess":before-upload="beforeAvatarUpload"><img v-if="imageUrl" :src="imageUrl" class="avatar" /><i v-else class="el-icon-plus avatar-uploader-icon"></i></el-upload></div><script>var app = new Vue({el:"#app",data(){return {imageUrl:""};},methods: {handleAvatarSuccess(res, file){this.$message.success("上傳頭像成功");this.imageUrl = URL.createObjectURL(file.raw);},beforeAvatarUpload(file) {const isJPG = file.type === 'image/jpeg';const isLt2M = file.size / 1024 / 1024 < 2;if(!isJPG){this.$message.error("上傳頭像圖片只能是 JPG 格式!");}if(!isLt2M){this.$message.error("上傳頭像圖片大小不能超過 2MB!");}return isJPG && isLt2M;}},})</script> </body> </html>總結
以上是生活随笔為你收集整理的koa --- 使用koa-multer上传文件+elementUI的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 商城GW-SHOP,基于 微信小程序 +
- 下一篇: koa --- 使用Sequelize