elementui-upload自定义上传方式上传到服务器返回url:http

本文介绍了一个使用Vue封装的图片上传组件,该组件利用Element UI的上传模块实现,并支持自定义上传逻辑。文章详细展示了如何限制文件类型和大小,以及如何通过Vue的v-model特性实现父组件与子组件之间的数据绑定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1-先封装一个uploadImage.vue组件
<template>
     <div class="photo">
        <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :http-request="handleUpload">
            <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar"> -->
            <img v-if="value" :src="value" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </div>
</template>
<script lang="ts">
// v-model 的本质 还是父子组件通信
// 1.他会给子组件传递一个名字叫做 value 的数据
// 2.默认监听input 事件修改绑定的数据
import Vue from 'vue'
import { uploadImage } from '@/services/user'
export default Vue.extend({
  props: {
    value: String
  },
  data () {
    return {
      imageUrl: ''
    }
  },
  methods: {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    handleAvatarSuccess (res: any, file: any) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    beforeAvatarUpload (file: any) {
      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
    },
    // 自定义上传方式 handleUpload
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    async handleUpload (options: any) {
      console.log(options, 'options')
      const fd = new FormData()
      fd.append('image', options.file) // file名称是后端接口传递的参数 名称file 默认也是file
      const res = await uploadImage(fd)
      console.log(res)

      // 上传给父组件
      this.$emit('input', res.data.data.url)
    }
  }
})
</script>
<style lang="scss" scoped>
 ::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  ::v-deep .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .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>

2-在父组件中引入 upload组件
/* eslint-disable @typescript-eslint/no-explicit-any */
<template>
  <div class="course">
    <CourseImage v-model="imageUrl"></CourseImage>
  </div>
</template>

<script lang="ts">

import Vue from 'vue'
import CourseImage from './components/CourseImage.vue'
export default Vue.extend({
  name: 'Course',
  components: {
    CourseImage
  },
  data () {
    return {
      imageUrl: '',
      course: {
        courseListImg: null
      }
    }
  }

})
</script>

<style lang="scss" scoped>

</style>

### 实现上传的功能 在 Vue3 和 Element Plus 中,`el-upload` 组件支持种配置选项以满足不同的需求。为了实现上传功能,可以通过调整 `limit`、`multiple` 等属性以及监听事件来完成。 以下是基于提供的引用内容和官方文档的一个完整示例: #### HTML 结构 ```html <template> <div> <!-- 使用 el-upload --> <el-upload action="https://jsonplaceholder.typicode.com/posts/" multiple :limit="3" list-type="picture-card" :on-exceed="handleExceed" :file-list="fileList" :auto-upload="false" :before-upload="beforeUpload"> <el-icon><Plus /></el-icon> </el-upload> <el-button style="margin-top: 20px;" @click="submitUpload">上传</el-button> </div> </template> ``` #### JavaScript 部分 ```javascript <script setup> import { ref } from 'vue'; import { ElMessage } from 'element-plus'; const fileList = ref([]); // 文件列表 // 超过限制时的回调函数 const handleExceed = () => { ElMessage.warning('最只能上传三张片'); }; // 自定义校验逻辑 const beforeUpload = (file) => { const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png'; if (!isJPGorPNG) { ElMessage.error('仅允许上传 JPG 或 PNG 格式的片!'); } const isLt2M = file.size / 1024 / 1024 < 2; if (!isLt2M) { ElMessage.error('片大小不能超过 2MB!'); } return isJPGorPNG && isLt2M; }; // 提交上传按钮点击事件 const submitUpload = () => { console.log(fileList.value, '待上传文件列表'); // 可在此处调用自定义方法提交到服务器 }; </script> ``` --- #### 关键参数说明 - **`action`**: 设置上传的目标 URL 地址[^1]。 - **`multiple`**: 是否允许选文件,默认为 `false`。将其设为 `true` 即可开启上传模式。 - **`list-type`**: 上传组件展示样式,常见的有 `"text"`(默认)、`"picture"` 和 `"picture-card"`。 - **`:limit`**: 限定最大上传数量,超出会触发 `exceed` 方法。 - **`:on-exceed`**:上传文件数超限时触发的方法。 - **`:before-upload`**:上传前对文件进行验证的操作钩子[^2]。 - **`:auto-upload`**: 控制是否自动上传文件。如果设置为 `false`,则需要手动触发表单提交操作。 --- #### 注意事项 当 `auto-upload` 设为 `false` 时,`before-upload` 不会被触发。因此,在这种情况下,建议将所有的校验逻辑放在其他地方处理,比如通过表单提交的方式统一管理。 另外,实际项目中可能还需要对接 OSS 接口或其他存储服务。此时可以参考引用中的代码片段[^3],动态生成上传地址并绑定成功后的回调函数。 --- ###
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值