1. Obtain the image file selected by the user according to input

let _file = this.$refs.input.files[0]

2. Stream the _file file through FileReader to base64

/** * base64 * @param {file}sourceImage object * @param {number} quality Image quality * @return{promise} promise */export const fileToBase64ByQuality = (file, quality) => {
  let fileReader = new FileReader()
  let type = file.type
  return new Promise((resolve, reject) => {
    if (window.URL || window.webkitURL) {
      resolve(compress(URL.createObjectURL(file), quality, type))}else {
      fileReader.onload = () => {
        resolve(compress(fileReader.result, quality, type))
      }
      fileReader.onerror = (e) => {
        reject(e)
      }
      fileReader.readAsDataURL(file)
    }
  })
}Copy the code

3, processing base64 data through canvas (toDataURL) compression drawing, and then output the compressed Base64 picture data

Const MAX_WIDTH = 800 /** * base64 compression (image-canvas interturn) * @param {file} base64 base64 image data * @param {number} quality Image quality * @param {string} format Output image format * @return{base64} data Base64 */ after image processingexport const compress = (base64, quality, mimeType) => {
  let cvs = document.createElement('canvas')
  let img = document.createElement('img')
  img.crossOrigin = 'anonymous'
  returnNew Promise((resolve, reject) => {img. SRC = base64 // image offsetlet offetX = 0
    img.onload = () => {
      if (img.width > MAX_WIDTH) {
        cvs.width = MAX_WIDTH
        cvs.height = img.height * MAX_WIDTH / img.width
        offetX = (img.width - MAX_WIDTH) / 2
      } else {
        cvs.width = img.width
        cvs.height = img.height
      }
      let ctx = cvs.getContext("2d").drawImage(img, 0, 0, cvs.width, cvs.height)
      let imageData = cvs.toDataURL(mimeType, quality / 100)
      resolve(imageData)
    }
  })
}Copy the code

Finally, base64 data is converted into bloB file stream

/** * base64 file transfer * @param {base64} Base64 data * @param {string} format Format * @return{file} file blob */export const convertBase64UrlToBlob = (base64, mimeType) => {
  let bytes = window.atob(base64.split(', ') [1])let ab = new ArrayBuffer(bytes.length)
  let ia = new Uint8Array(ab)
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i)
  }
  let _blob = new Blob([ab], { type: mimeType })
  return _blob
}Copy the code

5. Construct FormData data to upload files

let formData = new window.FormData()
formData.append('file', _blob)Copy the code