vue+element-ui+ koa-multer 上传图片
作者:互联网
const router = require('koa-router')()
const multer = require('koa-multer')
router.prefix('/upload')
//配置
var storage = multer.diskStorage({
//文件保存路径
destination: function(req, file, cb) {
//存储目录是手动建的 好像没办法自动建立二级目录
cb(null, './public/uploads/')
},
//修改文件名称
filename: function(req, file, cb) {
var fileFormat = (file.originalname).split(".");
cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
}
})
//加载配置
var upload = multer({ storage: storage });
//路由
router.post('/uploadimage', upload.single('file'), async(ctx, next) => {
ctx.body = {
fileData: ctx.req.file,
}
})
module.exports = router
前端页面 是用elementui 的上传组件
<el-upload
class="avatar-uploader"
//上传的地址
action="http://127.0.0.1:3000/upload/uploadimage"
:show-file-list="false"
//需要的请求头
:headers="headers"
: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>
JS
//设置请求头
computed: {
headers() {
return {
Authorization: "Bearer " + localStorage.getItem("token"),
};
},
},
标签:vue,koa,cb,element,multer,file,router,fileFormat 来源: https://blog.csdn.net/weixin_49675710/article/details/121251678