核心代码

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
const koa = require('koa');
const app = new koa();
const router = new require('koa-router')();
const multer = require('koa-multer');
const nunjucks = require('koa-nunjucks-2');
const path = require('path');
const fs = require('fs');// nunjucks的配置
app.use(nunjucks({ext: 'html',path: __dirname,nunjucksConfig: {trimBlocks: true}
}));// upload的配置
const upload = multer({dest: 'uploads/'
});const types = upload.single('avatar');
router.get('/upload', async (ctx, next) => {await ctx.render('upload')
})router.post('/profile', types, async  (ctx, next) => {const { originalname, path: out_path, mimetype} = ctx.req.file;let newName = out_path + path.parse(originalname).ext;let err = fs.renameSync(out_path, newName);let result;if(err){result = JSON.stringify(err);} else {result = `<h1>upload success</h1>`;}ctx.body = result;
});app.use(router.routes());app.listen(3000, async () => {console.log('Server is running at http://localhost:3000');
})
  • /upload.html
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>Document</title>
</head><body><form method="post" action="/profile" enctype="multipart/form-data">选择图片: <input name="avatar" id="upfile" type="file" /><input type="submit" value="提交" /></form>
</body></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="data: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相关推荐

  1. vue+axios+nodejs+multer上传文件的坑

    在做前后端分离的项目时.我们就不能使用form表单来提交数据或者上传文件了,那么就只能通过vue的axios来提交数据,如果数据中有文件类型的数据,就需要将所有需要上传的数据添加到FormData对象 ...

  2. node_上传文件multer+上传文件Ajax+文件下载

    非原创 本文转自https://github.com/a415432669/-front_end_notebook/tree/master/Node/day6/%E6%96%87%E6%A1%A3 一 ...

  3. koa上传文件处理403

    `403`一般是上传文件过大导致 > 使用koa-body 解决 `koa`的话,如 ``` const koaBody = require('koa-body') app.use(koaBod ...

  4. 七牛云配置 koa 上传文件到七牛云

    一.七牛云配置 七牛官网 1.创建七牛存储空间 2.空间添加备案的域名 (若是测试空间可不需要配置) 3.解析CNAME 添加域名后会有CNAME(别名记录),需要将它解析到你的备案域名下 链接-CN ...

  5. element-ui upload组件 上传文件类型限制

    element-ui upload组件 上传文件类型限制 <el-uploadclass="c-upload"ref="upload":action=&q ...

  6. axios 上传文件_聚是一团火散作满天星,前端Vue.js+elementUI结合后端FastAPI实现大文件分片上传...

    原文转载自「刘悦的技术博客」https://v3u.cn/a_id_175 分片上传并不是什么新概念,尤其是大文件传输的处理中经常会被使用,在之前的一篇文章里:python花式读取大文件(10g/50 ...

  7. ElementUI上传文件和额外参数

    ElementUI 上传文件和额外参数 需求是: 现有一后端接口,POST类型,参数为 @RequestParam("file") MultipartFile file,int c ...

  8. vue+elementui 同时有上传文件和批量上传文件功能,上传文件或批量上传文件后必须刷新才能再次上传文件

    报错描述: 使用element-ui的上传文件组件写一个批量上传和上传文件,但是发现每次上传文件后或者批量上传文件后,不能再次上传文件或者批量上传文件.只有进入页面第一次点击上传文件或者批量上传文件才 ...

  9. nodejs下上传文件formidable、multer、body-parser的区别

    Express 用于处理请求体的中间件很多,除了标题中提到的三个,还有multiparty.busboy等,multiparty性能上不如busboy,而multer是busboy的顶层封装,效率又提 ...

最新文章

  1. JQuery选择器 属性值 等于 以开头 以结尾 元素选择
  2. 【CEO赠书】《精益数据分析》:如何构建数据指标体系
  3. DDD关键知识点整理汇总
  4. TrackFormer解读
  5. YII2 实现后台操作记录日志
  6. acl在内核里的位置_Windows 注入篇 之 内核 APC 注入
  7. Respond.js让IE6-8支持CSS3 Media Query
  8. 字符设备驱动(四)按键中断
  9. web 请求 编码 引发的问题
  10. 集合竞价如何买入_世界上最稳健的抓涨停方法“10分钟集合竞价”选股诀窍,买入直接稳赚10个点,赚到笑...
  11. cf500B New Year Permutation
  12. Naive Bayes text classification
  13. JAVA时间格式化处理_java时间格式化处理
  14. CNI插件之bridge plugin
  15. 五分钟GO、KEGG和COG注释和富集分析
  16. 正负号 substr java_实战LeetCode 系列(一) (题目+解析)
  17. PHP:执行 PHP 文件
  18. 发扑克牌java程序_Java实现简易扑克牌游戏
  19. C语言用双曲线函数拟合曲线,c语言绘制函数曲线
  20. 物联网通信技术原理第5章 移动通信技术

热门文章

  1. php 四舍五入百位,php取整函数ceil,floor,round,intval函数的区别
  2. python3 console input_Python3 tkinter基础 Button command 单击按钮 在console中打印文本
  3. linux中自动挂载脚本,LIUNX一键自动挂载脚本,宝塔磁盘LIUNX一键分区磁盘 | 帮助信息-动天数据...
  4. 小米网关控制空调伴侣_小爱同学怎么控制灯?
  5. 树莓派python开发工具哪个好_Thonny——树莓派上Python的最新IDE
  6. gorm preload 搜索_文件太多忘记了文件放在什么地方?那你可以试试这款文件搜索工具...
  7. GPU Gems2 - 2 使用基于GPU几何体裁剪图的地形渲染(Terrain Rendering Using GPU-Based Geometry Clipmaps)
  8. 软工作业PSP与单元测试训练
  9. LeetCode 424. Longest Repeating Character Replacement
  10. 点击显示隐藏盒子函数