阿里云oss上传图片实现方案

该文章展示了如何在Vue组件中实现图片的多选上传功能,利用ali-oss库将图片上传到阿里云OSS。代码中包括了文件大小的校验、图片列表的管理以及上传状态的控制,采用Promise和async/await两种方式处理异步上传。
摘要由CSDN通过智能技术生成

跨域设置

来源 通配符* /服务器地址

 

<template>
  <div :class="$options.name">
    <!-- <button>选择图片上传</button> -->
    <label class="choose-img" :class="{ isUploading: isUploading }" for="upload"
      >选择图片上传</label
    >
    <input
      id="upload"
      type="file"
      accept="image/*"
      multiple
      style="display: none"
      ref="file"
      :disabled="isUploading"
      @change="onChange"
    />
    <p class="tip">
      提示:一次可选择多张图片,最多不超过9张(单张图片大小&lt; 1M)
    </p>
    <ul class="img-container">
      <li
        v-for="(item, index) of imgList"
        :key="index"
        :style="{ background: `url(${item}) no-repeat center center` }"
      ></li>
    </ul>
  </div>
</template>

<script>
// npm i --save ali-oss
import OSS from "ali-oss";
const ACCESSKEY = {
  ID: "***",
  SECRET: "***",
};
export default {
  name: "Upload",
  data() {
    return {
      client: new OSS({
        region: "***", // 区域
        bucket: "***", // bucket名称
        accessKeyId: ACCESSKEY.ID,
        accessKeySecret: ACCESSKEY.SECRET,
      }),
      imgList: [], // 存放上传完成的图片列表
      isUploading: false, // 图片是否正在上传中
    };
  },
  methods: {
    onChange() {
      // const fileDom = this.$refs.file;
      // console.log('触发上传-dom元素',fileDom);
      const newFiles = this.$refs?.file?.files;
      //   console.log("newFiles", newFiles);
      if (newFiles?.length > 9) {
        alert("最多可以一次选择9张图片");
        return false;
      }
      // 校验大小
      const files = [];
      for (const file of newFiles) {
        const size = file.size / 1024 / 1024; // 把单位转化成M
        if (size > 1) {
          alert("请选择1M以内的图片");
          return false;
        }
        files.push(file);
      }
      //   this.uploadFilesByOss(files);
      this.uploadFilesByOss2(files);
    },
    // 方式一:上传多图到阿里云OSS
    uploadFilesByOss(files) {
      // 上传aliyun
      this.isUploading = true;
      const uploadRequest = []; // 手机promise集合
      for (const file of files) {
        uploadRequest.push(
          new Promise((resolve, reject) => {
            // 第一个参数是文件名称,不能重复,加随机数
            // 第二个参数是上传文件本身
            this.client
              .put(`${Math.random()}-${file.name}`, file)
              .then((res) => {
                console.log(res);
                // console.log("---->", this.imgList);
                resolve(res.url);
              })
              .catch((err) => {
                // console.log(err);
                reject(err);
              });
          })
        );
      }
      Promise.allSettled([...uploadRequest])
        .then((res) => {
          console.log(res);
          const fulfilledImgs = [];
          if (res && res instanceof Array) {
            res.filter((item) => {
              if (item.status === "fulfilled") {
                fulfilledImgs.push(item.value);
              }
            });
          }
          this.imgList = [...this.imgList, ...fulfilledImgs]; // 展示页面数据
          this.isUploading = false;
        })
        .catch((err) => {
          console.log(err);
          this.isUploading = false;
        });
    },

    // // 方式二:上传多图到阿里云OSS,方法改写优化 async / await
    async uploadFilesByOss2(files) {
      this.isUploading = true;
      const imgs = [];
      console.log(1);
      for (const file of files) {
        const result = await this.client.put(
          `${Math.random()}-${file.name}`,
          file
        );
        imgs.push(result.url);
        console.log(2);
      }
      console.log(3);
      this.imgList = [...this.imgList, ...imgs];
      this.isUploading = false;
    },
  },
};
</script>
<style scoped>
.choose-img {
  display: block;
  width: 150px;
  height: 50px;
  text-align: center;
  line-height: 50px;
  background-color: #42b983;
  color: #fff;
  border-radius: 5px;
  cursor: pointer;
}
.tip {
  color: #ccc;
}
.img-container > li {
  list-style: none;
  width: 150px;
  height: 100px;
  float: left;
  margin: 0 30px 30px 0;
  border: 1px solid #ccc;
  background-position: center center;
  object-fit: unset;
}
.isUploading {
  background-color: #ccc;
}
</style>

上传成功

设置读写权限

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

短暂又灿烂的

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值