element-ui 图片(图片压缩)与文件上传设置【添加请求头信息】

发布于:2024-05-09 ⋅ 阅读:(33) ⋅ 点赞:(0)

1.图片上传

<template>
  <div>
    <el-upload class="avatar-uploader" :action="upload + '/Api/upload'" :show-file-list="false" :on-success="upSuccess"
      :before-upload="beforeAvatarUpload" :on-exceed="handleExceed" :on-preview="handlePreview" :disabled="disabled"
      :before-remove="beforeRemove" accept="image/*" :headers="headers">
      <img v-if="fileList" :src="mubanurl + fileList" class="avatar" :style="{ width: width, height: height }">
      <i v-else class="el-icon-plus avatar-uploader-icon" :style="{ width: width, height: height }"></i>
    </el-upload>
    <div>能上传图片类型:'jpg', 'jpeg', 'png', 'gif' , 图片大小: 10M ( 规格:150*50</div>
  </div>
</template>
<script>
import { upload, mubanurl } from '@/api/common.js'
import CryptoJS from '@/assets/js/hash.js'
import {
  compressImgNew
} from "@/assets/js/picture.js";
export default {
  data() {
    return {
      upload: upload,
      mubanurl: mubanurl,
      fileList: '',
      headers: {},
    }
  },
  props: {
    limit: {
      type: Number,
      default: 1,
    },
    uploadtype: {
      type: String,
      default: 'image',
    },
    showfilelist: {
      type: Boolean,
      default: true,
    },
    width: {
      type: String,
      default: '80px',
    },
    height: {
      type: String,
      default: '80px',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  mounted() {
  },
  computed: {},
  methods: {
    upSuccess(res, file) {
      this.fileList = ''
      if (res.code == 0) {
        this.fileList = res.data.filepath
        this.$emit('upload_file', res.data.filepath)
        this.$message.success(res.message);
      } else {
        this.$message.error(res.message);
        return
      }
    },
    beforeAvatarUpload(file) {
      let types = [
        "image/jpeg",
        "image/jpg",
        "image/png"
      ];
      const isImage = types.includes(file.type);
      const isLtSize = file.size / 1024 / 1024 < 5;
      if (!isImage) {
        this.$message.warning("上传图片只能是 JPG、JPEG、PNG 格式!");
        return false;
      }
      if (!isLtSize) {
        this.$message.warning("上传图片大小不能超过 5MB!");
        return false;
      }

      // 获取当前日期
      var currentDate = new Date();

      // 格式化日期为 'YYYY-MM-DD' 格式
      var formattedDate = currentDate.getFullYear() + '-' +
        String(currentDate.getMonth() + 1).padStart(2, '0') + '-' +
        String(currentDate.getDate()).padStart(2, '0');

      var password = CryptoJS.MD5("li-tong-gas-" + formattedDate);
      // 使用示例
      // var password = "bd557960c173bdaf7a9df9e7fa55a4a8";
      var hashedPassword = this.hashPassword(password);
      this.headers = {
        "x-api-key": hashedPassword,
        "token": localStorage.getItem("admintoken")
      }

      return compressImgNew(file);
    },
    hashPassword(password) {
      var salt = CryptoJS.lib.WordArray.random(16); // 生成随机盐
      var hash = CryptoJS.SHA256(password + salt); // 使用 SHA256 算法对密码和盐进行哈希
      var hashWithSalt = salt.toString() + hash.toString(); // 将盐和哈希值连接起来
      return hashWithSalt;
    },
    handlePreview(file) {
      console.log(file, '点击查看');
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 ${this.limit} 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}`);
    },
  },
}
</script>
<style lang='less' scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  // width: 80px;
  // height: 80px;
  // line-height: 80px;
  // text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 80px;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>

1.1 图片压缩文件

   // "crypto-js": "^4.2.0",
import CryptoJS from 'crypto-js';

// 图片压缩
export const compressImgNew = (file) => {
  return new Promise(resolve => {
    const reader = new FileReader()
    const image = new Image()
    image.onload = (imageEvent) => {
      const canvas = document.createElement('canvas') // 创建画布
      const context = canvas.getContext('2d')         // 画布为2d
      const width = image.width / 1.05        // 图片宽度 / 压缩比例
      const height = image.height / 1.05        // 图片高度 / 压缩比例
      canvas.width = width                            // 画布宽度
      canvas.height = height                          // 画布宽度
      context.clearRect(0, 0, width, height)
      context.drawImage(image, 0, 0, width, height)
      const dataUrl = canvas.toDataURL(file.type)     //图片转路径
      const blobData = dataURLtoBlob(dataUrl, file.type) //图片转二进制
      resolve(blobData)
    }
    reader.onload = e => { image.src = e.target.result }
    reader.readAsDataURL(file)
  })
};

//图片转二进制
function dataURLtoBlob(dataURL, type) {
  var binary = atob(dataURL.split(',')[1])
  var array = []
  for (var i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i))
  }
  return new Blob([new Uint8Array(array)], { type: type })
}


// 登录加密
export function encrypt(data) {
  let key = MD5(process.env.VUE_APP_BASE_KEY)
  // key = MD5('wu-jie-de-you-xi-dev')
  var x = 0
  var len = data.length
  var l = data.length
  var char = ''
  var str = ''
  for (var i = 0; i < len; i++) {
    if (x === l) {
      x = 0
    }
    char += key.charAt(x)
    x++
  }
  for (var j = 0; j < len; j++) {
    str += String.fromCharCode(data.charCodeAt(j) + (char.charCodeAt(j) % 256))
  }
  return btoa(str)
}

function MD5(data) {
  const hashedPassword = CryptoJS.MD5(data).toString()
  return hashedPassword
}



2.文件上传

<template>
  <div>
    <!-- :file-list="fileList" :limit="limit" -->
    <el-upload
      class="upload-demo"
      :action="upload + '/Api/uploadFile'"
      :on-preview="handlePreview"
      :disabled="disabled"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      multiple
      :on-exceed="handleExceed"
      :on-success="upSuccess"
      :before-upload="beforeAvatarUpload"
      :show-file-list="false"
      :file-list="fileList"
      :headers="headers"
    >
      <el-button size="mini" type="primary">点击上传</el-button>
    </el-upload>
    <div>能上传文件类型:xlsx ,word ,Excel ,图片 ,pdf文件大小: 20M</div>
  </div>
</template>
<script>
import { upload, mubanurl } from "@/api/common.js";
import CryptoJS from "@/assets/js/hash.js";
export default {
  data() {
    return {
      upload: upload,
      mubanurl: mubanurl,
      url: "",
      srcList: [],
      // headers: {},
    };
  },
  props: {
    limit: {
      type: Number,
      default: 1,
    },
    uploadtype: {
      type: String,
      default: "image",
    },
    // 编辑数据
    fileList: {
      type: Array,
      default: () => [],
    },
    showfilelist: {
      type: Boolean,
      default: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  mounted() {},
  computed: {
    headers() {
      // 获取当前日期
      var currentDate = new Date();

      // 格式化日期为 'YYYY-MM-DD' 格式
      var formattedDate =
        currentDate.getFullYear() +
        "-" +
        String(currentDate.getMonth() + 1).padStart(2, "0") +
        "-" +
        String(currentDate.getDate()).padStart(2, "0");

      var password = CryptoJS.MD5("li-tong-gas-" + formattedDate);
      // 使用示例
      // var password = "bd557960c173bdaf7a9df9e7fa55a4a8";
      var hashedPassword = this.hashPassword(password);
      let obj = {
        "x-api-key": hashedPassword,
        token: localStorage.getItem("admintoken"),
      };
      return obj;
    },
  },
  methods: {
    upSuccess(res, file) {
      if (res.code == 0) {
        this.$emit("upload_file", {
          fileurl: res.data.filepath,
          name: file.name,
        });
      } else {
        this.$message.error(res.message);
        return;
      }
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      // 文件限制: 'doc', 'xls', 'xlsx', 'pdf', 'ppt', 'pptx', 'docx'  文件大小: 20M
      const filesize = file.size / 1024 / 1024;
      if (filesize > 20) {
        this.$message.error("上传图片大小不能超过 20MB!");
        return;
      }
      // this.headers = {
      //   "x-api-key": hashedPassword,
      //   token: localStorage.getItem("admintoken"),
      // };

      // console.log(this.headers, 123);
      return file;
    },
    hashPassword(password) {
      var salt = CryptoJS.lib.WordArray.random(16); // 生成随机盐
      var hash = CryptoJS.SHA256(password + salt); // 使用 SHA256 算法对密码和盐进行哈希
      var hashWithSalt = salt.toString() + hash.toString(); // 将盐和哈希值连接起来
      return hashWithSalt;
    },
    handleRemove(file, fileList) {
      let ary = [];
      fileList.forEach((it) => {
        ary.push(it.response.data.filepath);
      });
      // this.$emit('upload_file_clear', ary)
    },
    handlePreview(file) {
      console.log(file, "点击查看");
    },
    handleExceed(files, fileList) {
      this.$message.warning(`请删除之前上传的文件后,再继续上传!`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}`);
    },
  },
};
</script>
<style lang="less" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>


网站公告

今日签到

点亮在社区的每一天
去签到