iview upload 上传多张图片 ,图片存在oss服务器上

在这里插入图片描述
在这里插入图片描述

upload-img.vue

<template>
  <div class="uploader-container">
    <div class="demo-upload-list" v-for="(item, index) in uploadList" :key="index">
      <template v-if="item.status === 'finished'">
        <img :src="item.url" />
        <div class="demo-upload-list-cover">
          <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
          <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
        </div>
      </template>
      <template v-else>
        <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
      </template>
    </div>
    <Upload
      ref="upload"
      style="display: inline-block;width:58px;"
      :default-file-list="defaultFileList"
      :multiple="true"
      accept="image/*"
      :format="['jpg', 'png', 'jpeg']"
      :show-upload-list="false"
      type="drag"
      :action="uploadUrl"
      :name="fileFieldName"
      :data="extraParams"
      :before-upload="handleBeforeUpload"
      :on-format-error="handleFormatError"
      :on-success="handleSuccess"
      :on-error="handleError"
    >
      <div style="width: 58px;height:58px;line-height: 58px;">
        <Icon type="ios-cloud-upload" size="20"></Icon>
      </div>
    </Upload>
    <Modal title="查看大图" v-model="visible">
      <img :src="imgName" v-if="visible" style="width: 100%" />
    </Modal>
  </div>
</template>

<script>
import randomize from 'randomatic';
import { getOssSignature } from 'api/oss';

export default {
  props: {
    maxNum: {
      default: 9,
      type: Number,
    },
    defaultList: {
      // 默认文件列表
      default: function() {
        return [];
      },
      type: Array,
    },
  },
  data() {
    return {
      uploadUrl: this.$https
        ? 'https://oss.oss-cn-hangzhou.aliyuncs.com'
        : 'http://oss.oss-cn-hangzhou.aliyuncs.com',
      uploadList: [],
      defaultFileList: [],
      tmpUploadFile: {},
      fileNum: 0,
      fileFieldName: 'file',
      extraParams: {
        key: '',
        policy: '',
        OSSAccessKeyId: '',
        success_action_status: 200,
        callback: '',
        signature: '',
      },
      imgName: '',
      visible: false,
      uidList: {},
    };
  },
  computed: {
    uploadFile: {
      get() {
        return this.initSingleFile;
      },
      set(file) {
        this.initSingleFile = file;
      },
    },
  },
  watch: {
    defaultList(newVal) {
      this.defaultFileList = newVal;
      this.uploadList = newVal;
      this.uploadList.map(item => {
        this.uidList[item.name] = {
          filename: item.name,
          filetype: 'png',
          fileurl: item.url,
          suffix: 'png',
        };
      });
      this.fileNum += this.defaultList.length;
    },
  },
  mounted() {
    this.uploadList = this.$refs.upload.fileList;
    this.uploadList.map(item => {
      this.uidList[item.name] = {
        filename: item.name,
        filetype: 'png',
        fileurl: item.url,
        suffix: 'png',
      };
    });
  },
  methods: {
    handleView(name) {
      this.imgName = name;
      this.visible = true;
    },
    handleRemove(file) {
      const fileList = this.$refs.upload.fileList;
      this.uploadList = fileList;
      this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
      let cpFileList = fileList.map(file => this.uidList[`${file.name}`]);
      this.$emit('file-remove', {
        fileList: cpFileList,
      });
      this.fileNum--;
    },
    handleBeforeUpload(file) {
      const check = this.fileNum < this.maxNum;
      // 用自己定义的 fileNum 计数,beforeUpload 加1
      // 别用官方提供的 this.uploadList.length ,有坑
      if (!check) {
        this.$Message.error(`最多只能上传 ${this.maxNum} 个文件`);
        return false;
      }
      this.fileNum++;
      return this.prefixParams(file);
    },
    prefixParams(file) {
      let fileNameArray = file.name.split('.');
      let fileType = fileNameArray[fileNameArray.length - 1];
      let fileName = file.name.slice(0, -fileType.length - 1);
      return getOssSignature()
        .then(res => {
          let data = JSON.parse(res.data);
          let randomNum = randomize('Aa0', 15);
          this.extraParams.policy = data.policy;
          this.extraParams.OSSAccessKeyId = data.accessid;
          this.extraParams.signature = data.signature;
          this.extraParams.key = `${data.dir}${randomNum}.${fileType}`;

          this.uploadUrl = data.host;
          if (this.$https && this.uploadUrl.indexOf('https') < 0) {
            this.uploadUrl = this.uploadUrl.replace('http', 'https');
          }
          this.uidList[file.name] = {
            fileurl: `${this.uploadUrl}/${this.extraParams.key}`,
            //filetype: this.mapFileType(fileType),
            filetype: fileType,
            suffix: fileType,
            filename: fileName,
          };
        })
        .catch(error => {
          console.error(error);
        });
    },
    handleSuccess(event, file, fileList) {
      this.$emit('isShow');
      this.uploadList = fileList;
      file.url = this.uidList[`${file.name}`].fileurl;
      let cpFileList = fileList.map(file => this.uidList[`${file.name}`]);
      this.$emit('upload-success', {
        file: this.uidList[`${file.name}`],
        fileList: cpFileList,
      });
    },
    handleError(event, file) {
      delete this.uidList[`${file.name}`];
      this.fileNum--;
    },
    handleFormatError(file) {
      this.$emit('format-error', file);
    },
  },
};
</script>

<style lang="scss" type="text/scss">
.uploader-container {
  width: 100%;
  height: 100%;
  position: relative;
  .ivu-upload {
    height: 100%;
  }
}
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
.upload-zone {
  padding: 20px 0;
  &__icon {
    color: #3399ff;
  }
}
</style>

<upload-img2 :defaultList="defaultList" :maxNum="6" @file-remove="syncFileList" @upload-success="syncFileList"></upload-img2>


import uploadImg2 from './upload-img.vue'; 
components: {
    uploadImg2
},
data() {
	return {
	defaultList: [],
	}
}
methods: {
    // 同步上传组件中的文件列表(添加和移除)
    syncFileList({ fileList }) {
      // 配置每个任务的picList
      console.log("syncFileListsyncFileListsyncFileList=======",fileList);
      this.defaultList = fileList;
    },
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值