el-upload---上传/下载图片

发布时间 2023-03-27 14:54:35作者: 会转圈圈的哆瑞米

上传照片

          <el-upload
            ref="upload"
            :file-list="fileList"
            action="#"
            :auto-upload="false"
            :on-change="handleChange"
            :on-remove="handleRemove"
            :limit="2"
            list-type="picture-card"
          >
            <i
              class="el-icon-plus"
              :style="{ display: fileList.length ? 'none' : 'inline-block' }"
            ></i>
            <span
              :style="{ display: fileList.length ? 'inline-block' : 'none' }"
              >点击重新选择</span
            >
          </el-upload>

  data: () => {
    return {
      newData: {},
      fileList: [], //图片信息
    };
  },

//
上传照片
methods:{
async addData() { let condition
= new FormData(); condition.append("fileId", this.info.fileId); condition.append("id", this.info.id); condition.append("comment", this.comment); condition.append("files", this.fileList[0]?.raw || await this.Base64ToFile(this.fileList[0]?.url, this.fileList[0]?.name)); uploadFile(condition) .then((res) => { if (res.data.code === 200) { this.$message.success("上传成功!"); this.$emit("successHandle") } else { this.$message.error(res.data.message); } }) .catch((error) => { this.$message.error({ message: failResponse(error).message, }); }); }, // 将base64转换为file Base64ToFile(dataurl, fileName) { const arr = dataurl.split(","), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]); let n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new File([u8arr], fileName, { type: mime }); },
 
    handleChange(files, fileList) {
      if (fileList.length > 1) { //限制只可上传一张
        fileList.splice(0, 1);
      }
      this.fileList = fileList;
    },
    handleRemove(files, fileList) {
      this.fileList = [];
    },

}

 查看照片

// 查看照片
    getData() {
      getFile({
        fileId: this.info.fileId,
      })
        .then((res) => {
          this.comment = res.data.data.comment;
          this.fileList = [{name: res.data.data.fileName, url: 'data:image/png;base64,'+this.ArrayBufferToBase64(res.data.data.files)}]
        })
        .catch((error) => {
          this.$message.error({
            message: failResponse(error).message,
          });
        });
    },

// byte数组转字符串
    ArrayBufferToBase64(buffer) {
      // 第一步:将arrayBuffer转为二进制字符串
      let binary = '';
      let bytes = new Uint8Array(buffer);
      for (let len = bytes.byteLength, i =0; i<len;i++) {
        binary += String.fromCharCode(bytes[i]);
      }
      // 将二进制字符串转为base64字符串
      return window.btoa(binary);
    },