uniapp上传图片封装

在子组件components里创建upload.vue文件

<template>
  <view class="uploadImage">
    <view class="item-box">
      <view @tap="previewImg(item)" v-for="(item, index) in imgList" :key="item" class="item">
        <image mode="aspectFill" :src="item"></image>
        <view class="img-del" @tap.stop="delImg(index)">
          <uni-icons type="clear" size="20"></uni-icons>
        </view>
      </view>
      <view @tap="choseImg" class="item"><image src="https://autoservice-prod.oss-cn-beijing.aliyuncs.com/img/common/upload.png"></image></view>
    </view>
  </view>
</template>

<script>
// import store from '../store';
import config from '../config'; 

export default {
  props: {
    value: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      imgList: []
    };
  },
  methods: {
    delImg(index) {
      this.imgList.splice(index, 1);
    },
    imgCount(arr = []) {
      let imgList = this.imgList;
      if (imgList.length > 3 || imgList.length + arr.length > 3) {
        this.$toast('最多选择三张图片');
        return false;
      }
      if (arr.length) {
        this.imgList = this.imgList.concat(arr);
      }
      return true;
    },
    choseImg() {
      let _this = this;
      if (!_this.imgCount()) {
        return;
      }
      let currentImgIndex = _this.imgList.length;
      let count = 3 - _this.imgList.length;
      if (count <= 0) {
        return this.$toast('最多选择三张图片');
      }
      uni.chooseImage({
        count: count, //默认9
        success: function(res) {
          _this.imgCount(res.tempFilePaths);
          _this.uploadImg(res.tempFilePaths, currentImgIndex);
        }
      });
    },
    uploadImg(tempFilePaths, currentImgIndex) {
      let _this = this;
      uni.showLoading({
        title: '图片上传中'
      });
      let promiseArr = tempFilePaths.map((item, index) => {
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: config.apiUrl + '/api/admin/app/oss/uploadImg', //图片上传地址
            filePath: item, //要上传文件资源的路径。
            header: {
              Token: encodeURIComponent(uni.getStorageSync('Token')) //请求头
            },
            // header: {
            //     'content-type': 'multipart/form-data' 
            // },
            formData: {
              objectNamePrefix: 'upload/easyjoy_store/' //HTTP 请求中其他额外的 form data
            },
            name: 'files',
            success(response) {  //成功回调
              response = JSON.parse(response.data);
              if (response.statusCode === 200) {
                _this.imgList[currentImgIndex + index] = response.data.url;
                resolve();
              } else {
                _this.imgList.splice(currentImgIndex + index, 1);
                _this.$toast('图片上传失败');
                reject('图片上传失败');
              }
            },
            fail() { //失败回调
              _this.imgList.splice(index, 1);
              _this.$toast('图片上传失败');
              reject('图片上传失败');
            }
          });
        });
      });
      Promise.all(promiseArr).finally(() => {
        _this.$emit('input', _this.imgList);
        uni.hideLoading();
      });
    },
    previewImg(url) {
      uni.previewImage({
        urls: this.imgList,
        current: url
      });
    }
  }
};
// 详细文档请查阅官网 https://uniapp.dcloud.net.cn/api/request/network-file.html#uploadfile
// 注意:如果在微信小程序开发的时候上传图片没问题,发布到体验版或者正式版的时候进入失败回调的话,前往微信公众平台查看服务器上传地址有没有配置上传白名单。
</script>

<style lang="less">
.uploadImage {
  margin-top: 40rpx;
  .item-box {
    display: flex;
    flex-wrap: wrap;
  }
  image {
    width: 120rpx;
    height: 120rpx;
  }
  .item {
    position: relative;
    width: 120rpx;
    height: 120rpx;
    margin-right: 20rpx;
    margin-bottom: 20rpx;
  }
  .img-del {
    position: absolute;
    top: -10rpx;
    right: -10rpx;
  }
}
</style>

在要使用的父组件引入

<template>
    <view>
        <template v-for="(item,index) in pictureUrl">
              <image style="width: 132rpx; height: 132rpx; background-color: #eeeeee; margin-left: 10rpx;" :key='index' :src="item" @error="imageError"></image>
        </template>
    </view>
    <view>
        <upload v-model="pictureUrl" />
    </view>
</template>

<script>    
import upload from '@/components/upload.vue';
export default {
    components: {
        upload
    },
    data() {
        return {
            pictureUrl: [], //存储的图片地址
        }
    }
}
</script>

猜你喜欢

转载自blog.csdn.net/zzll1216/article/details/128903633