【工具】vue 图片上传(单张/多张)

本文单传组件取自若依微服务为版ruoyi-ui:http://doc.ruoyi.vip/ruoyi-cloud/

环境:

  • vue@2.6.12 
  • element-ui@2.15.3

1.图片上传(单张) 

组件:

//components/ImageUpload

<template>
  <div class="component-upload-image">
    <el-upload
      accept=".png,.jpg,.jpeg"
      :action="uploadImgUrl"
      list-type="picture-card"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :on-error="handleUploadError"
      name="file"
      :show-file-list="false"
      :headers="headers"
      style="display: inline-block; vertical-align: top"
    >
      <el-image v-if="!value" :src="value">
        <div slot="error" class="image-slot">
          <i class="el-icon-plus" />
        </div>
      </el-image>
      <div v-else class="image">
        <el-image :src="value" :style="`width:150px;height:150px;`" fit="fill"/>
        <div class="mask">
          <div class="actions">
            <span title="预览" @click.stop="dialogVisible = true">
              <i class="el-icon-zoom-in" />
            </span>
            <span title="移除" @click.stop="removeImage">
              <i class="el-icon-delete" />
            </span>
          </div>
        </div>
      </div>
      <!-- 上传提示 -->
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        请上传
        <template v-if="fileSize">
          大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
        </template>
        <template v-if="fileType">
          格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
        </template>
        的文件
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" title="预览" width="800" append-to-body>
      <img :src="value" style="display: block; max-width: 100%; margin: 0 auto;">
    </el-dialog>
  </div>
</template>

<script>
/**
 * 图片单传
 */
import { getToken } from "@/utils/auth";
export default {
  data() {
    return {
      dialogVisible: false,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileType: ["png", "jpg", "jpeg"]
    };
  },
  props: {
    value: {
      type: String,
      default: "",
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
  },
  computed:{
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    }
  },
  methods: {
    removeImage() {
      this.$emit("input", "");
    },
    handleUploadSuccess(res) {
      this.$emit("input", res.data.url);
      this.loading.close();
    },
    handleBeforeUpload() {
      this.loading = this.$loading({
        lock: true,
        text: "上传中",
        background: "rgba(0, 0, 0, 0.7)",
      });
    },
    handleUploadError() {
      this.$message({
        type: "error",
        message: "上传失败",
      });
      this.loading.close();
    },
  },
  watch: {},
};
</script>

<style scoped lang="scss">
.image {
  position: relative;
  .mask {
    opacity: 0;
    position: absolute;
    top: 0;
    width: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    transition: all 0.3s;
  }
  &:hover .mask {
    opacity: 1;
  }
}
</style>

 使用:

import ImageUpload from '@/components/ImageUpload';

export default {
  components: {
    ImageUpload
  }
}

<template>
   <imageUpload v-model="form.imageUrl" />
</template>

结果呈现:

2.图片上传(多张)

该组件基于若依微服务版ruoyi-ui进行改造 

组件代码:

//components/PictureCard

<template>
  <div class="upload-picture-card" :key="fileKey">
    <el-upload
      multiple
      ref="pictureCard"
      accept=".png, .jpg, .jpeg"
      :action="uploadImgUrl"
      :headers="headers"
      :file-list="fileList"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-upload="handleBeforeUpload"
      :on-error="handleUploadError"
      :on-success="handleUploadSuccess"
      list-type="picture-card"
    >
      <i class="el-icon-plus"></i>
      <!-- 上传提示 -->
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        请上传
        <template v-if="fileSize">
          大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
        </template>
        <template v-if="fileType">
          格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
        </template>
        的文件
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" title="预览" width="800" append-to-body>
      <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto;">
    </el-dialog>
  </div>
</template>
<script>
/**
 * 图片多传
 */
import { getToken } from "@/utils/auth";
export default {
  props: {
    //值
    value: {
      type: Array,
      default(){
        return []
      },
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl:'',
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileType: ["png", "jpg", "jpeg"],
      fileList: [],
      fileKey: Math.random()
    };
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
    // 列表
    list: {
      get: function() {
        let temp = 1;
        if (this.value) {
          // 首先将值转为数组
          const list = Array.isArray(this.value) ? this.value : [this.value];
          // 然后将数组转为对象数组
          return list.map((item) => {
            if (typeof item === "string") {
              item = { name: item, url: item };
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      set: function() {
      }
    },
    valueList(){
      return this.value;
    }
  },
  watch:{
    value:{
      handler(newVal){
        if(!newVal || newVal.length <= 0)this.fileKey = Math.random();  //利用随机数清除组件缓存
      },
      deep: true,
      immediate: true
    },
    list:{
      handler(newVal){
        this.fileList = newVal;
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$message.error(
            `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`
          );
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    // 预览
    handlePreview(file){
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 删除
    handleRemove(file, fileList){
      const url = file.response ? file.response.data.url : file.url;
      const index = this.valueList.findIndex(v => v == url);
      if(index != -1)this.valueList.splice(index,1);
      
      this.$emit("input", this.valueList);
    },
    // 上传失败
    handleUploadError(err) {
      this.$message.error("上传失败, 请重试");
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      this.$message.success("上传成功");
      //this.$emit("input", res.data.url);
      this.valueList.push(res.data.url);
      this.$emit("input",this.valueList);
    },
  },
};
</script>
<style>
.el-upload__tip {
  line-height: 1.2;
}
</style>

 使用:

import PictureCard from '@/components/PictureCard';

export default {
 components: {
    PictureCard,
  }
}

<template>
  <!--该数组中存储为图片url-->
  <PictureCard v-model="form.imgArray"/>
</template>

结果呈现:

 

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
回答: 在Vue2中,可以使用Vant 2这个基于Vue的移动UI组件库来实现上传多张图片的功能。首先,你需要在相关文档中找到上传照片的代码段,其中使用了van-uploader组件来实现图片上传的功能。\[1\]你可以将这段代码添加到你的Vue组件中,并根据需要进行相应的配置,比如设置最多上传4张照片、设置最大文件大小等。然后,你还需要引入一个名为PictureCard的组件,并在Vue组件的components选项中注册这个组件。\[2\]在你的Vue模板中,你可以使用PictureCard组件来展示已上传的图片,并通过v-model指令来绑定一个数组,用于存储图片的URL。这样,用户就可以通过上传按钮选择并上传多张图片了。 #### 引用[.reference_title] - *1* [vue2 + vant2 实现上传图片功能](https://blog.csdn.net/m0_56976301/article/details/130339181)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [vue上传图多张图片功能](https://blog.csdn.net/weixin_44274094/article/details/126719120)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值