SoFunction
Updated on 2025-04-06

vue image compression and batch upload method

vue image compression and batch upload

Use the el-upload component

Supports batch upload and image compression.

The front-end needs to introduce image-conversion

  • multiple set to true to allow batch uploads
  • Set auto-upload to false to turn off automatic upload

Verify file name and file size when on-change

Add a button to upload to the server

<template>
  <div class="">
    <el-upload ref="pictureUpload"
               :multiple="true"
               :action="uploadFileUrl"
               list-type="picture-card"
               :disabled="check"
               :on-change="handleOnChange"
               :before-upload="beforUpload"
               :on-success="handleUploadSuccess"
               :auto-upload="false"
               :file-list="showFile">
      <i slot="default"
         class="el-icon-plus"></i>
      <div slot="file"
           slot-scope="{file}">
        <img class="el-upload-list__item-thumbnail"
             :src=""
             alt="">
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview"
                :disabled="true"
                @click="handlePictureCardPreview(file)">
            <i class="el-icon-zoom-in"></i>
          </span>
          <span v-if="!check"
                class="el-upload-list__item-delete"
                @click="handleRemoveThis(file)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </el-upload>
    <el-button style="margin-left: 10px;"
               size="small"
               v-if="!check"
               type="success"
               @click="submitUpload">Submit the image to the server</el-button>
    <el-dialog :="dialogVisible"
               title="Preview"
               width="800"
               append-to-body>
      <img :src="dialogImageUrl"
           style="display: block; max-width: 100%; margin: 0 auto;">
    </el-dialog>
  </div>
</template>
 
<script>
import { getToken } from "@/utils/auth";
import * as imageConversion from 'image-conversion';
import { delImg } from "@/api/system/vote"
export default {
  name: 'jImageUpload',
  props: ['imageUrl', 'check'],
  data () {
    return {
      AllLoading: [],
      oldImg: null,
      dialogImageUrl: '',
      checkUpload: false,
      fileList: [],
      returnFileList: [],
      showFile: [],
      urlStr: [],
      editFile: [],
      dialogVisible: false,
      uploadFileUrl: .VUE_APP_BASE_API + "/sys/minio/upload", // Uploaded image server address      headers: {
        Authorization: "Bearer " + getToken(),
      },
    };
  },
  mounted () { // Assign values ​​when mounted, the child component is only updated once. After re-selecting, the data of this component will be displayed and will not be updated.     = 
    ()
  },
  watch: {
    imageUrl: function (val) {
      // // ('val')
      // // (val)
       = val
      ()
    }
  },
  created () {
  },
  methods: {
    stringToImage (imageString) {
       = []
       = []
      if (imageString != null && imageString != '' && imageString != undefined) {
         = (",");
        (item => {
          let obj = new Object();
          let obj1 = new Object();
           = item;
          if (("http") < 0) {
            item = .VUE_APP_BASE_MINIO_API + item;
          }
           = item;
          (obj);
          (obj1);
        });
      }
    },
    arryToString (arry) {
      var imgString = ""
      if ( > 0) {
        for (var i = 0; i < ; i++) {
          if (i <  - 1) {
            imgString += arry[i].url + ",";
          } else {
            imgString += arry[i].url
          }
        }
      }
      return imgString
    },
    // Click to view the picture    handlePictureCardPreview (file) {
       = ;
       = true;
    },
    handleOnChange (file, fileList) {
      if ((',') !== -1) {
        ("English commas are not allowed in the uploaded file name!");
        (file)
        return false
      } else {
        const isLt2M =  / 1024 / 1024 < 1;
        if (!isLt2M) {
          (file)
          // return new Promise((resolve) => {
          // Compress to 600KB, the 600 here is the size to be compressed, which can be customized          (, 600).then(res => {
             = new ([res], , { type:  })
             = 
            (file)
          });
          // })
        } else {
          (file)
        }
      }
    },
    // File upload    submitUpload () {
      // Full screen disable on       = this.$loading({
        lock: true,
        text: 'Image uploading...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      let fileList = []
      let { uploadFiles, action, data } = this.$
      // (uploadFiles)
      // (file => {
      //   (, 600).then(res => {
      //      = new ([res], , { type:  })
      //      = 
      //   });
      // })
      // (uploadFiles)
      ({
        uploadFiles,
        data,
        action,
        success: (response) => {
          var res = (response)
          // this.$();
          // (res)
          ("The picture upload was successful!")
          ()
          (item => {
            let obj = new Object();
            let obj1 = new Object();
             = .VUE_APP_BASE_MINIO_API + item;
             = item;
            (obj1)
            (obj)
            var imgString = ()
            this.$emit('returnUrl', imgString)
          })
        },
        error: (error) => {
          ("Image upload failed!")
          ()
          ('The upload of the picture failed!  ', error)
        }
      })
    },
    /**
      * Custom upload files
      * @param fileList file list
      * @param data Additional parameters included when uploading
      * @param url Uploaded URL address
      * @param success callback
      * @param error Failed callback
      */
    uploadFiles ({ uploadFiles, headers, data, action, success, error }) {
      let form = new FormData()
      // File object      (file => ("filedatas", ))
      // Attachment parameters      for (let key in data) {
        (key, data[key])
      }
      let xhr = new XMLHttpRequest()
      // Asynchronous request      ("post", action, true)
      // Set request header      ("Authorization", getToken());
       = function () {
        if ( == 4) {
          if (( >= 200 &&  < 300) ||  == 304) {
            success && success()
          } else {
            error && error()
          }
        }
      }
      (form)
    },
    // Remove the picture    handleRemoveThis (file) {
      // (file)
      // Remove image from the control      this.$(file)
      // Get the position of the image in the array      var number = (file)
      // Get the URL of this file in the returned file url      var file = .VUE_APP_BASE_MINIO_API + [number].()
      var fileItemList = ('/')
      // Execute file deletion      delImg(fileItemList[4]).then(response => {
        // // (response)
      })
      (number, 1)
      (number, 1)
      var imgString = ()
 
      this.$emit('returnUrl', imgString)
    },
    // Before uploading    beforUpload (file) {
      ("Before uploading")
      (file)
      if ((',') !== -1) {
        ("English commas are not allowed in the uploaded file name!");
        return false
      } else {
        //  = true
        (file)
        const isLt2M =  / 1024 / 1024 < 1;
        if (!isLt2M) {
          return new Promise((resolve) => {
            // Compress to 100KB, the 100 here is the size to be compressed, which can be customized            (, 600).then(res => {
              resolve(res);
            });
          })
        }
      }
    },
    // Upload successfully    handleUploadSuccess (res, file, fileList) {
      //  = false
      // ("Uploaded successfully")      // (res)
      // (fileList)
      (this.$)
      this.$("Uploaded successfully");
      // (item => {
      //   let obj = new Object();
      //   let obj1 = new Object();
      //   if ( !== undefined) {
      //      = .VUE_APP_BASE_MINIO_API + ;
      //      = ;
      //     (obj1)
      //     (obj)
      //     var imgString = ()
      //     this.$emit('returnUrl', imgString)
      //   }
      // })
      let obj = new Object();
      let obj1 = new Object();
       = .VUE_APP_BASE_MINIO_API + ;
       = ;
      (obj1)
      (obj)
      var imgString = ()
      this.$emit('returnUrl', imgString)
    },
    handleUploadError () {
      this.$message({
        type: "error",
        message: "Upload failed",
      });
      ();
    },
  },
};
</script>
 
<style scoped lang="scss">
.image {
  position: relative;
  .mask {
    opacity: 0;
    position: absolute;
    top: 0;
    width: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    transition: all 0.3s;
  }
  &:hover .mask {
    opacity: 1;
  }
}
</style>

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.