圖片壓縮並上傳


1、壓縮方法公共js

/** 圖片壓縮,默認同比例壓縮
 *  @param {Object} fileObj
 *  圖片對象
 *  回調函數有一個參數,base64的字符串數據
 */
 export function compress(fileObj, callback) {
  try {
    const image = new Image()
    image.src = URL.createObjectURL(fileObj)
    image.onload = function() {
      const that = this
      // 默認按比例壓縮
      let w = that.width
      let h = that.height
      const scale = w / h
      w = fileObj.width || w
      h = fileObj.height || (w / scale)
      let quality = 0.7 // 默認圖片質量為0.7
      // 生成canvas
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      // 創建屬性節點
      const anw = document.createAttribute('width')
      anw.nodeValue = w
      const anh = document.createAttribute('height')
      anh.nodeValue = h
      canvas.setAttributeNode(anw)
      canvas.setAttributeNode(anh)
      ctx.drawImage(that, 0, 0, w, h)
      // 圖像質量
      if (fileObj.quality && fileObj.quality <= 1 && fileObj.quality > 0) {
        quality = fileObj.quality
      }
      // quality值越小,所繪制出的圖像越模糊
      const data = canvas.toDataURL('image/jpeg', quality)
      // 壓縮完成執行回調
      const newFile = convertBase64UrlToBlob(data)
      callback(newFile)
    }
  } catch (e) {
    console.log('壓縮失敗!')
  }
}
function convertBase64UrlToBlob(urlData) {
  const bytes = window.atob(urlData.split(',')[1]) // 去掉url的頭,並轉換為byte
  // 處理異常,將ascii碼小於0的轉換為大於0
  const ab = new ArrayBuffer(bytes.length)
  const ia = new Uint8Array(ab)
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i)
  }
  return new Blob([ab], { type: 'image/png' })
}

 

2、el-upload上傳組件

<el-upload
  name="file"
  class="upload"
  list-type="picture-card"
  action="#"
  accept="image/jpeg, image/jpg, image/png"
  :file-list="fiilList"
  :on-change="uploadChange"
  :multiple="false"
  :limit="1"
  :auto-upload="false"
>

 

3、js部分

import { compress } from '@/utils/compress.js'
import { AjaxUploadImg } from '@/utils/uploadImg.js'
uploadChange(file, fileList) {
      const _this = this;
      const isLt1M = file.size / 1024 / 1024 < 1;
      // 上傳圖片不能大於1M
      if (!isLt1M) {
     console.log('上傳圖片不能大於1M')
     return false; } else { const isLt04 = file.size / 1024 / 1024 > 0.4; // 上傳圖片大於400KB再壓縮 if(isLt04) { // 壓縮圖片 compress(file.raw, function(val) { let params = { file: val, type: 1, id: _this.officialInfo.id } _this.uploadImg(params, file.name, fileList); }) } else { let params = { file: file.raw, type: 1, id: _this.officialInfo.id } _this.uploadImg(params, file.name, fileList); } } }, uploadImg(params, fileName, fileList) { const _this = this; AjaxUploadImg(_this.uploadUrl, params, fileName, function(res) { let data = JSON.parse(res) if(data.code==200){ console.log('上傳成功!') } else { _this.$message.error("圖片上傳失敗!"); } }); },

 

封裝的請求方式:uploadImg.js

/** 
 * 原生AJAX請求
 * 上傳圖片
 * url     服務器地址
 * data    傳遞的參數
 * imgName 圖片名稱
 * fn      返回的數據
 */
// bus為vue對象
import bus from "./bus";
export function AjaxUploadImg(url, data, imgName, fn) {
  let formData = new FormData();
  for (const key in data) {
    if(key == 'file'){
      // 判斷是否為blob對象
      if(data[key] instanceof Blob){
        // blob對象轉file對象
        let files = new window.File([data[key]], imgName)
        formData.append('file', files);
      } else {
        formData.append('file', data[key]);
      }
    } else {
      formData.append(key, data[key]);
    }
  }
  // 建立請求
  var xhr = new XMLHttpRequest();
  xhr.open("POST", url, true);
  xhr.setRequestHeader("Authorization", "Bearer " + bus.$cookieGet("TOKEN"));
  xhr.onreadystatechange = function() {
    if(xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
      fn.call(this, xhr.responseText);
    }
  };
  xhr.send(formData);
}

 

PS:壓縮方法公共js來源於https://blog.csdn.net/liona_koukou/article/details/84860899

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM