element 图片上传 oss 后端签名 前端直传



 //图片上传拿签名
    async picUpload(file) {
      let pro = new Promise((resolve, rej) => {
        // 判断签名有没有过期
        var res = JSON.parse(localStorage.getItem("sign"));
        var timestamp = Date.parse(new Date()) / 1000;
        if (res && res.expire - 3 > timestamp) {
          resolve(res);
        } else {
          getJsPolicy().then(res => {
            if (res.code == 200) {
              localStorage.setItem("sign", JSON.stringify(res.data));
              resolve(res.data);
            }
          });
        }
      });
      var that = this;
      pro.then(success => {
        var data = success;
        var ossData = new FormData();
        ossData.append("name", file.file.name);
        //key就代表文件层级和阿里云上的文件名
        let imgType = file.file.type.split("/")[1];
        let filename = file.file.name + file.file.size; //md5对图片名称进行加密
        let keyValue = data.dir + "/" + md5(filename) + "." + imgType;
        ossData.append("key", keyValue);
        ossData.append("policy", data.policy);
        ossData.append("OSSAccessKeyId", data.accessid);
        ossData.append("success_action_status", 201);
        ossData.append("signature", data.signature);
        ossData.append("file", file.file, file.file.name);
        axios
          .post(data.host, ossData, {
            headers: {
              "Content-Type": "multipart/form-data"
            }
          })
          .then(res => {
            if (res.status == 201) {  //上传成功 上传的路径就是要使用的路径 
              let url = data.host + "/" + keyValue;
              let pic = {
                url: url
              };
              this.picList.push(pic);
            }
          })
          .catch(error => {});
      });
    },
uploadBefore(file) {
      //上传文件之前校验图片格式和大小
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/gif" ||
        file.type === "image/jpg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG、JPEG、PNG、GIF 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过2MB!");
        return false;
      }
    },

 

你可能感兴趣的:(前端框架,前端开发)