elkers
2025-01-16 0b62eca817d6c40c188dc72c3034835a61a30a35
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<!--
 * @Author: Liuyi candymxq888@outlook.com
 * @Date: 2024-08-08 10:29:19
 * @LastEditors: Liuyi candymxq888@outlook.com
 * @LastEditTime: 2024-10-14 10:47:17
 * @FilePath: \water-qinghe-web\src\components\upload\uploadIcon.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <el-upload class="uploader" :show-file-list="false"
    :before-upload="beforeAvatarUpload" :http-request="uploadImg">
    <img v-if="imageUrl" :src="imageUrl"/>
    <el-icon v-else class="uploader-icon">
      <Plus />
    </el-icon>
  </el-upload>
</template>
 
<script setup>
import { Plus } from '@element-plus/icons-vue'
import { upload } from '@/api/basicApi/index'
import { PREURL } from '@/config/index'
const { proxy } = getCurrentInstance();
const preUrl = PREURL
const props = defineProps({
  image: {
    type: String,
    default: ''
  }
})
const emit = defineEmits(['uploadData'])
const imageUrl = ref('')
 
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    proxy.$modal.msgError('图片大小不能超过2MB!')
    return false
  }
  return true
}
//上传图片调用接口
const uploadImg = async (params) => {
  //建立表单,请求参数传表单形式
  let form = new FormData();
  form.append("file1", params.file);
  form.append("fileId", params.file.lastModified);
  form.append("path", 'qinghe');
  //发出上传文件请求
  let res = await upload().uploadFile(form)
  if (res.code == 200) {
    //返回的图片网络地址传给form
    proxy.$modal.msgSuccess('上传图片成功')
    imageUrl.value = res.data.newFileName
    emit('uploadData', imageUrl.value)
  }
}
onMounted(() => {
  imageUrl.value = ''
})
// 监听props.image
watch(props, (newImgUrl) => {
  if(newImgUrl.image != ''){
    imageUrl.value = preUrl + newImgUrl.image
  }else{
    imageUrl.value = ''
  }
}, { immediate: true })
</script>
<style lang="scss">
.el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    img {
      width: 100px;
      height: 100px;
    }
    .el-icon.uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      text-align: center;
    }
  }
 
</style>