vue 纯前端 上传图片到七牛云

1.template

<template>
  <div>
         <el-upload
            class="avatar-uploader"
            ref="upload"
            multiple
            :auto-upload="true"
            :action="domain"
            :limit="10"
            accept="image/jpeg,image/png,image/bmp,image/jpg"
            :file-list="fileList"
            :show-file-list="true"
            :data="QiNiuYun"
            :on-preview="picCardPreview"
            :before-upload="beforePicUpload"
            :on-exceed="handleExceed"
            :on-remove="removePic"
            :http-request="uploadQiniu"
          > 
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-dialog append-to-body :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
  </div>
</template>

2.script

<script>
import axios from "axios";
export default {
 data() {
    return { 
      dialogVisible: false,  
      QiNiuYun: {
        //上传图片携带的参数
        token: "",
        key: "",
      },
      domain: "",
      fileList: [],
      dialogImageUrl: "",   
    };
  },
},
  methods: {
  //上传图预览
    picCardPreview(file, fileList) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //图片校验
    beforePicUpload(file) {
      const limitPic =
        file.type === "image/png" ||
        file.type === "image/jpg" ||
        file.type === "image/jpeg" ||
        file.type === "image/bmp";
      if (!limitPic) {
        this.$notify.warning({
          title: "警告",
          message: "请上传格式为image/png,image/jpg,image/jpeg,image/bmp的图片",
        });
      }
      const limitSize = file.size / 1024 / 1024 / 2 < 2;
      if (!limitSize) {
        this.$notify.warning({
          title: "警告",
          message: "图片大小必须小于2M",
        });
      }
      return limitPic && limitSize;
    },
    //文件超出个数限制
    handleExceed() {
      this.$notify.warning({
        title: "警告",
        message: "一次只能上传十张图片",
        duration: 2000,
      });
    },
    //移除图片
    removePic(file, fileList) {
      this.fileList = fileList;
    }, 
    //上传七牛云
    uploadQiniu(request) {
      this.handleUpload(request)
        .then((res) => {
          if (res) {
            console.log("success", res);
          } else {
            this.$message.error({
              message: "图片上传失败,请重新上传",
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          this.$message.error({
            message: `图片上传失败${err}`,
            duration: 2000,
          });
        });
    },
    handleUpload(request) {
      const promise = new Promise((resolve, reject) => {
        let fileType = "";
        if (request.file.type === "image/jpg") {
          fileType = "jpg";
        } else if (request.file.type === "image/png") {
          fileType = "png";
        } else if (request.file.type === "image/jpeg") {
          fileType = "jpeg";
        }
        //自定义图片名
        const key = `front_${new Date().getTime()}${Math.floor(
          Math.random() * 100
        )}.${fileType}`;
        // 获取token
        this.$request("getToken", { fileName: key })
          .then((res) => {
            this.domain = res.domain;
            const fd = new FormData();
            fd.append("file", request.file);
            fd.append("token", res.uptoken);
            fd.append("key", res.filePath);
            const config = {
              headers: {
                "Content-Type": "multipart/form-data",
              },
            };
            axios
              .post(this.domain, fd, config)
              .then((res) => {
                if (res.status == 200 && res.data) {
                  let a = {
                    path: res.data.key,
                    photoRemark: "",
                  };
                  resolve(res);
                } else {
                  reject(res);
                }
              })
              .catch((err) => {
                this.$message.error({
                  message: `上传失败[${err.status}]`,
                  duration: 2000,
                });
              });
            resolve(true);
          })
          .catch((err) => {});
      });
      return promise;
    },
}
</script>

猜你喜欢

转载自blog.csdn.net/future_1_/article/details/128198970