13.koa-文件上传

289 阅读1分钟

安装koa-multer

npm i koa-multer -S

使用

  • html
<el-upload class="avatar-uploader" name='avatar' action="/user/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>
        
const vm = new Vue({
    el: '#app',
    data() {
        return {
            imageUrl: '',
        }
    },

    methods: {
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        }
    }
})
  • user.js
//文件上传
const multer = require('koa-multer');
//配置 磁盘存储
const storage = multer.diskStorage({
    //文件保存路径
    destination: function (req, file, cb) {
        cb(null, 'public/images/')
    },
    //修改文件名称,让上传的文件名字统一
    filename: function (req, file, cb) {
        var fileFormat = (file.originalname).split("."); //以点分割成数组,数组的最后一项就是后缀名
        cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
    }
})
//加载配置
const upload = multer({
    storage: storage
});
//单文件上传
router.post('/upload', upload.single('avatar'), (ctx, next) => {
    // ctx.req.file  是avatar文件的信息
    // ctx.req.body 文本域数据 如果存在
    //  ctx.body = '上传成功';
    console.log(ctx.req.file.filename);
    ctx.body = {
        ok: 1
    }
})