Improve user experience: Vue and compressor.js achieve efficient file compression

foreword

Uploading files is a common requirement, and file size often becomes one of the limiting factors. In order to improve user experience and save bandwidth consumption, file compression during upload is particularly important. This article will introduce the implementation method of file compression during upload based on the Vue framework and compressor.js. By compressing the file during the upload process, the file size can be reduced, the upload speed can be improved, and a faster and more efficient upload experience can be created for users .


Install

npm install image-compressor.js
yarn add image-compressor.js

Compressor.js common properties

Attributes describe
quality Sets the quality of compressed images. Values ​​range from 0 to 1, where 0 is the lowest quality and 1 is the highest quality.
width Specifies the target width for compressed images. Can be expressed in pixels or percentages.
height Specifies the target height for compressed images. Can be expressed in pixels or percentages.
minWidth Minimum value to limit compressed image width. If the image's width is smaller than this value, no compression will take place.
minHeight The minimum value to limit the height of the compressed image. If the height of the image is less than this value, no compression will be done.
maxWidth Limit the maximum width of the compressed image. If the image's width exceeds this value, it will be scaled down.
maxHeight Limits the maximum height of the compressed image. If the height of the image exceeds this value, it will be scaled down.
convertSize Determines whether images are resized when compressed. If set to true, the image will be automatically resized according to the target width and height.
checkOrientation Checks the image's orientation information and auto-rotates if necessary.

These are compressorjssome common properties of plugins that control the compression quality, size and orientation of images. You can set these properties according to actual needs to obtain the desired compression effect. For more details and properties, please refer to the plugin's official documentation .


package file

import ImageCompressor from 'image-compressor.js';

export default function compressFile(file) {
    
    
  return new Promise((resolve, reject) => {
    
    
    const options = {
    
    
      success(result) {
    
    
        // 将压缩后的 Blob 转换为 File 对象(如果组件支持Blob则不用这一步)
        const compressedFile = new File([result], file.name, {
    
    
          type: file.type,
          lastModified: Date.now(),
        });
        resolve(compressedFile);
      },
      error(e) {
    
    
        reject(e);
      },
    };
    if (file.size > 5 * 1024 * 1024) {
    
    
      options.quality = 0.6; // 压缩质量
      options.convertSize = false;//不进行图像尺寸的调整
      options.checkOrientation = false; // 图片翻转,默认为false
    }
    new ImageCompressor(file, options);
  });
}


main.js

// 全局挂载
import compressFile from '@/utils/compressFile';
Vue.prototype.$compressFile = compressFile;

use file

<template>
  <div>
    <van-field label="照片">
      <template #input>
        <van-uploader :after-read="(file, detail) => clzpAfterRead(file, detail, 'xszzp')" v-model="cszp" :max-count="1" accept="image/*" />
      </template>
    </van-field>
  </div>
</template>

<script>
import {
      
       uploadFile } from "@/api/publicApi";
export default {
      
      
  data() {
      
      
    return {
      
      
      cszp: "",
    };
  },
  mounted() {
      
      },
  methods: {
      
      
    async clzpAfterRead(file, detail, name) {
      
      
      console.log(file.file.size, "未压缩大小");
      // 调用压缩图片的方法 this.$compressFile
      const compressedFile = await this.$compressFile(file.file);
      console.log(compressedFile.size, "压缩后大小");
      let formData = new FormData();
      formData.append("file", compressedFile);
      uploadFile(formData).then((res) => {
      
      
        // 执行操作
      });
    },
  },
};
</script>

Implementation process

  1. First, the library needs to Vuebe imported into the component ImageCompressor. Can be import ImageCompressor from 'image-compressor.js'achieved through;
  2. Below is a compressFilefunction named . This function accepts a file ( file) as a parameter and returns an Promiseobject for handling asynchronous operations;
  3. Inside compressFilethe function, an object is created options, which contains callback functions for success ( success) and error ( );error
  4. If the size of the file exceeds 5MB, set the property optionsof the object to indicate the compression quality as ;quality0.660%
  5. Next, create an ImageCompressorinstance, optionspassing it the file and the object as parameters. This will trigger the image compression process;
  6. When the compression is successful, successthe callback function will be called. In the callback function, convert the compressed Blobobject to Filean object, and use resolvethe method to return it as Promisethe return value of ;
  7. When a compression error occurs, the callback function is called error. In the callback function, use rejectthe method to Promisereturn the error information as the return value of ;
  8. Next is Vuethe template code for a component. The component is used in the template van-uploaderto realize the image upload function;
  9. A method methodsnamed is defined in the attribute . clzpAfterReadThis method will be triggered after the image is uploaded successfully. Parameter fileindicates the uploaded file, detailindicates the detailed information of the upload, and nameindicates the name of the uploaded file;
  10. In clzpAfterReadthe method, first print out the original size of the uploaded file file.file.size. Next, call this.$compressFilethe method to compress the uploaded file;
  11. Use awaitthe keyword to wait for the compression operation to complete, and assign the compressed file to compressedFilethe variable;
  12. Print out the size of the compressed file compressedFile.size;
  13. Create a FormDataobject formDataand add the compressed file to it formData;
  14. Call uploadFilethe method, formDatapass it as a parameter, and use .thenthe method to process the response after the upload is successful;
  15. Subsequent operations can be performed in .thenthe method, such as updating the interface or processing successfully uploaded data.

To sum up, the implementation idea of ​​this code is: van-uploaderimplement the image upload function through the component, call the method after the upload is successful clzpAfterRead, compress the uploaded image file through image-compressor.jsthe library, and upload the compressed file to the server again. The whole process uses Vuethe framework and Promiseobjects to handle asynchronous operations, so as to realize the function of compressing the image size when uploading.


achieve effect

insert image description here

Guess you like

Origin blog.csdn.net/Shids_/article/details/131855886