最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

vue圖片壓縮與批量上傳方式

 更新時(shí)間:2025年01月25日 08:39:45   作者:C8H9NO2  
文章介紹了使用Vue和Element UI的el-upload組件實(shí)現(xiàn)圖片的批量上傳和壓縮功能,前端需引入image-conversion庫(kù)并設(shè)置相關(guān)屬性,關(guān)閉自動(dòng)上傳,通過(guò)on-change事件校驗(yàn)文件名和大小,并增加一個(gè)提交到服務(wù)器的按鈕

vue圖片壓縮與批量上傳

使用el-upload組件

支持批量上傳和圖片壓縮。

前端需要引入 image-conversion

  • multiple設(shè)置為true,允許批量上傳
  • auto-upload設(shè)置為false,關(guān)閉自動(dòng)上傳

在on-change的時(shí)候校驗(yàn)文件名和文件大小

增加一個(gè)上傳到服務(wù)器的按鈕

<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="file.url"
             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">圖片提交到服務(wù)器</el-button>
    <el-dialog :visible.sync="dialogVisible"
               title="預(yù)覽"
               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: process.env.VUE_APP_BASE_API + "/sys/minio/upload", // 上傳的圖片服務(wù)器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
    };
  },
  mounted () { // 在mounted時(shí)候賦值,子組件只更新一次,后面重新選擇后展示此組件的數(shù)據(jù),不再更新
    this.oldImg = this.imageUrl
    this.stringToImage(this.oldImg)
  },
  watch: {
    imageUrl: function (val) {
      // // console.log('val')
      // // console.log(val)
      this.oldImg = val
      this.stringToImage(this.oldImg)
    }
  },
  created () {
  },
  methods: {
    stringToImage (imageString) {
      this.showFile = []
      this.editFile = []
      if (imageString != null && imageString != '' && imageString != undefined) {
        this.urlStr = imageString.split(",");
        this.urlStr.forEach(item => {
          let obj = new Object();
          let obj1 = new Object();
          obj1.url = item;
          if (item.indexOf("http") < 0) {
            item = process.env.VUE_APP_BASE_MINIO_API + item;
          }
          obj.url = item;
          this.showFile.push(obj);
          this.editFile.push(obj1);
        });
      }
    },
    arryToString (arry) {
      var imgString = ""
      if (arry.length > 0) {
        for (var i = 0; i < arry.length; i++) {
          if (i < arry.length - 1) {
            imgString += arry[i].url + ",";
          } else {
            imgString += arry[i].url
          }
        }
      }
      return imgString
    },
    // 點(diǎn)擊查看圖片
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleOnChange (file, fileList) {
      if (file.name.indexOf(',') !== -1) {
        this.msgError("上傳的文件名稱(chēng)中不允許出現(xiàn)英文逗號(hào)!");
        this.handleRemoveThis(file)
        return false
      } else {
        const isLt2M = file.size / 1024 / 1024 < 1;
        if (!isLt2M) {
          console.log(file)
          // return new Promise((resolve) => {
          // 壓縮到600KB,這里的600就是要壓縮的大小,可自定義
          imageConversion.compressAccurately(file.raw, 600).then(res => {
            file.raw = new window.File([res], file.name, { type: file.type })
            file.size = file.raw.size
            this.fileList.push(file)
          });
          // })
        } else {
          this.fileList.push(file)
        }
      }
    },
    // 文件上傳
    submitUpload () {
      // 全屏禁用開(kāi)啟
      this.AllLoading = this.$loading({
        lock: true,
        text: '圖片上傳中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      let fileList = []
      let { uploadFiles, action, data } = this.$refs.pictureUpload
      // console.log(uploadFiles)
      // uploadFiles.forEach(file => {
      //   imageConversion.compressAccurately(file.raw, 600).then(res => {
      //     file.raw = new window.File([res], file.name, { type: file.type })
      //     file.size = file.raw.size
      //   });
      // })
      // console.log(uploadFiles)
      this.uploadFiles({
        uploadFiles,
        data,
        action,
        success: (response) => {
          var res = JSON.parse(response)
          // this.$refs.uploadFile.clearFiles();
          // console.log(res)
          this.msgSuccess("圖片上傳成功!")
          this.AllLoading.close()
          res.data.fileName.forEach(item => {
            let obj = new Object();
            let obj1 = new Object();
            obj.url = process.env.VUE_APP_BASE_MINIO_API + item;
            obj1.url = item;
            this.editFile.push(obj1)
            this.showFile.push(obj)
            var imgString = this.arryToString(this.editFile)
            this.$emit('returnUrl', imgString)
          })
        },
        error: (error) => {
          this.msgError("圖片上傳失??!")
          this.AllLoading.close()
          console.log('圖片上傳失??!', error)
        }
      })
    },
    /**
     * 自定義上傳文件
     * @param fileList 文件列表
     * @param data 上傳時(shí)附帶的額外參數(shù)
     * @param url 上傳的URL地址
     * @param success 成功回調(diào)
     * @param error 失敗回調(diào)
     */
    uploadFiles ({ uploadFiles, headers, data, action, success, error }) {
      let form = new FormData()
      // 文件對(duì)象
      uploadFiles.map(file => form.append("filedatas", file.raw))
      // 附件參數(shù)
      for (let key in data) {
        form.append(key, data[key])
      }
      let xhr = new XMLHttpRequest()
      // 異步請(qǐng)求
      xhr.open("post", action, true)
      // 設(shè)置請(qǐng)求頭
      xhr.setRequestHeader("Authorization", getToken());
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
          if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
            success && success(xhr.responseText)
          } else {
            error && error(xhr.status)
          }
        }
      }
      xhr.send(form)
    },
    // 移除圖片
    handleRemoveThis (file) {
      // console.log(file)
      // 在控件中移除圖片
      this.$refs.pictureUpload.handleRemove(file)
      // 獲取圖片在數(shù)組中的位置
      var number = this.showFile.indexOf(file)
      // 獲取返回的文件url中此文件的url
      var file = process.env.VUE_APP_BASE_MINIO_API + this.editFile[number].url.toString()
      var fileItemList = file.split('/')
      // 執(zhí)行文件刪除
      delImg(fileItemList[4]).then(response => {
        // // console.log(response)
      })
      this.editFile.splice(number, 1)
      this.showFile.splice(number, 1)
      var imgString = this.arryToString(this.editFile)
 
      this.$emit('returnUrl', imgString)
    },
    // 上傳前
    beforUpload (file) {
      console.log("上傳之前")
      console.log(file)
      if (file.name.indexOf(',') !== -1) {
        this.msgError("上傳的文件名稱(chēng)中不允許出現(xiàn)英文逗號(hào)!");
        return false
      } else {
        // this.checkUpload = true
        this.fileList.push(file)
        const isLt2M = file.size / 1024 / 1024 < 1;
        if (!isLt2M) {
          return new Promise((resolve) => {
            // 壓縮到100KB,這里的100就是要壓縮的大小,可自定義
            imageConversion.compressAccurately(file.raw, 600).then(res => {
              resolve(res);
            });
          })
        }
      }
    },
    // 上傳成功
    handleUploadSuccess (res, file, fileList) {
      // this.checkUpload = false
      // console.log("上傳成功")
      // console.log(res)
      // console.log(fileList)
      console.log(this.$refs.pictureUpload.uploadFiles)
      this.$message.success("上傳成功");
      // fileList.forEach(item => {
      //   let obj = new Object();
      //   let obj1 = new Object();
      //   if (item.response !== undefined) {
      //     obj.url = process.env.VUE_APP_BASE_MINIO_API + item.response.fileName;
      //     obj1.url = item.response.fileName;
      //     this.editFile.push(obj1)
      //     this.showFile.push(obj)
      //     var imgString = this.arryToString(this.editFile)
      //     this.$emit('returnUrl', imgString)
      //   }
      // })
      let obj = new Object();
      let obj1 = new Object();
      obj.url = process.env.VUE_APP_BASE_MINIO_API + res.fileName;
      obj1.url = res.fileName;
      this.editFile.push(obj1)
      this.showFile.push(obj)
      var imgString = this.arryToString(this.editFile)
      this.$emit('returnUrl', imgString)
    },
    handleUploadError () {
      this.$message({
        type: "error",
        message: "上傳失敗",
      });
      this.loading.close();
    },
  },
};
</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>

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Vue.js實(shí)現(xiàn)對(duì)視頻預(yù)覽的示例代碼

    Vue.js實(shí)現(xiàn)對(duì)視頻預(yù)覽的示例代碼

    本文主要介紹了Vue.js實(shí)現(xiàn)對(duì)視頻預(yù)覽的示例代碼,通過(guò)監(jiān)聽(tīng)文件選擇事件和使用FileReader API,可以實(shí)現(xiàn)視頻文件的預(yù)覽功能,感興趣的可以了解一下
    2025-01-01
  • Element?Plus修改表格行和單元格樣式詳解

    Element?Plus修改表格行和單元格樣式詳解

    在使用Element Plus中的table組件展示數(shù)據(jù)時(shí),由于需要對(duì)表格行內(nèi)數(shù)據(jù)的數(shù)據(jù)進(jìn)行修改,下面這篇文章主要給大家介紹了關(guān)于Element?Plus修改表格行和單元格樣式的相關(guān)資料,需要的朋友可以參考下
    2022-04-04
  • 討論vue中混入mixin的應(yīng)用

    討論vue中混入mixin的應(yīng)用

    這篇文章主要介紹了vue中混入mixin的理解和應(yīng)用,對(duì)vue感興趣的同學(xué),可以參考下
    2021-05-05
  • 使用proxy實(shí)現(xiàn)一個(gè)更優(yōu)雅的vue【推薦】

    使用proxy實(shí)現(xiàn)一個(gè)更優(yōu)雅的vue【推薦】

    Proxy 用于修改某些操作的默認(rèn)行為,等同于在語(yǔ)言層面做出修改,所以屬于一種“元編程”。這篇文章主要介紹了用proxy實(shí)現(xiàn)一個(gè)更優(yōu)雅的vue,需要的朋友可以參考下
    2018-06-06
  • vue+uniapp實(shí)現(xiàn)生成二維碼

    vue+uniapp實(shí)現(xiàn)生成二維碼

    這篇文章主要為大家詳細(xì)介紹了vue結(jié)合uniapp實(shí)現(xiàn)生成二維碼的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的小伙伴可以學(xué)習(xí)一下
    2023-12-12
  • Vue項(xiàng)目請(qǐng)求超時(shí)處理方式

    Vue項(xiàng)目請(qǐng)求超時(shí)處理方式

    這篇文章主要介紹了Vue項(xiàng)目請(qǐng)求超時(shí)處理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • vue隱藏路由的實(shí)現(xiàn)方法

    vue隱藏路由的實(shí)現(xiàn)方法

    這篇文章主要介紹了vue隱藏路由的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • Vuex中的Mutation使用詳解

    Vuex中的Mutation使用詳解

    這篇文章主要介紹了Vuex中的Mutation使用詳解,當(dāng)我們想修改狀態(tài)值,想傳入的值進(jìn)而進(jìn)行修改時(shí),你可以向 store.commit 傳入額外的參數(shù),即 mutation 的 載荷,需要的朋友可以參考下
    2023-11-11
  • vue時(shí)間戳和時(shí)間的相互轉(zhuǎn)換方式

    vue時(shí)間戳和時(shí)間的相互轉(zhuǎn)換方式

    本文通過(guò)示例代碼介紹了vue時(shí)間戳和時(shí)間的相互轉(zhuǎn)換方式,通過(guò)場(chǎng)景分析介紹了vue3使用組合式api將時(shí)間戳格式轉(zhuǎn)換成時(shí)間格式(2023年09月28日 10:00),感興趣的朋友一起看看吧
    2023-12-12
  • 解決vue3?defineProps?引入定義的接口報(bào)錯(cuò)

    解決vue3?defineProps?引入定義的接口報(bào)錯(cuò)

    這篇文章主要為大家介紹了解決vue3?defineProps?引入定義的接口報(bào)錯(cuò)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-05-05

最新評(píng)論

天祝| 万全县| 沽源县| 平江县| 巴林右旗| 芮城县| 宣威市| 金门县| 聂拉木县| 西昌市| 德庆县| 正定县| 双城市| 库尔勒市| 济阳县| 湄潭县| 贺州市| 青浦区| 齐齐哈尔市| 安平县| 手游| 许昌县| 葵青区| 道真| 金昌市| 北海市| 墨脱县| 和田县| 铜山县| 盐津县| 泾源县| 安平县| 兴海县| 梁平县| 中牟县| 波密县| 同江市| 新竹市| 广饶县| 会泽县| 明溪县|