# 文件上传

下面是文件上传组件在vue3与element plus中的使用

  • 使用token进行身份验证
  • 使用vue setup语法

image-20210622021720037

<template>
    <div class="upload-image">
        <el-upload :action="action" :headers="headers" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <div v-if="imageUrl" class="image-container">
                <img :src="imageUrl" class="image-url" />
                <i class="fas fa-window-close fa-2x del-icon" @click.stop="del"></i>
            </div>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </div>
</template>

<script setup>
    import { ref } from 'vue'

    const action = import.meta.env.MODE == 'development' ? 'http://houdunren.test/api/upload' : '/api/upload'

    const headers = {
        Authorization: `Bearer ${window.localStorage.getItem('token')}`,
    }

    const imageUrl = ref('http://houdunren.test/attachment/2106/jpxPEU5hCcZKuJv0BsDFt1JIJ0W4hJ64SiJaWBUo.jpg')
    // const imageUrl = ref('')
    const handleAvatarSuccess = (res, file) => {
        imageUrl.value = file.response.data.path
    }

    const 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
    }

    const del = () => {
        imageUrl.value = ''
    }
</script>

<style lang="scss">
    .upload-image {
        position: relative;
        .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            &:hover {
                border-color: #409eff;
            }
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 150px;
            height: 150px;
            // line-height: 178px;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .avatar {
            width: auto;
            // height: 178px;
            display: block;
            background: #f3f3f3;
        }
        .image-container {
            .del-icon {
                position: absolute;
                right: 10px;
                top: 10px;
                color: #fff;
                cursor: pointer;
            }
            .image-url {
                max-height: 200px;
            }
        }
    }
</style>