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 compressorjs
some 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
- First, the library needs to
Vue
be imported into the componentImageCompressor
. Can beimport ImageCompressor from 'image-compressor.js'
achieved through; - Below is a
compressFile
function named . This function accepts a file (file
) as a parameter and returns anPromise
object for handling asynchronous operations; - Inside
compressFile
the function, an object is createdoptions
, which contains callback functions for success (success
) and error ( );error
- If the size of the file exceeds
5MB
, set the propertyoptions
of the object to indicate the compression quality as ;quality
0.6
60%
- Next, create an
ImageCompressor
instance,options
passing it the file and the object as parameters. This will trigger the image compression process; - When the compression is successful,
success
the callback function will be called. In the callback function, convert the compressedBlob
object toFile
an object, and useresolve
the method to return it asPromise
the return value of ; - When a compression error occurs, the callback function is called
error
. In the callback function, usereject
the method toPromise
return the error information as the return value of ; - Next is
Vue
the template code for a component. The component is used in the templatevan-uploader
to realize the image upload function; - A method
methods
named is defined in the attribute .clzpAfterRead
This method will be triggered after the image is uploaded successfully. Parameterfile
indicates the uploaded file,detail
indicates the detailed information of the upload, andname
indicates the name of the uploaded file; - In
clzpAfterRead
the method, first print out the original size of the uploaded filefile.file.size
. Next, callthis.$compressFile
the method to compress the uploaded file; - Use
await
the keyword to wait for the compression operation to complete, and assign the compressed file tocompressedFile
the variable; - Print out the size of the compressed file
compressedFile.size
; - Create a
FormData
objectformData
and add the compressed file to itformData
; - Call
uploadFile
the method,formData
pass it as a parameter, and use.then
the method to process the response after the upload is successful; - Subsequent operations can be performed in
.then
the method, such as updating the interface or processing successfully uploaded data.
To sum up, the implementation idea of this code is: van-uploader
implement the image upload function through the component, call the method after the upload is successful clzpAfterRead
, compress the uploaded image file through image-compressor.js
the library, and upload the compressed file to the server again. The whole process uses Vue
the framework and Promise
objects to handle asynchronous operations, so as to realize the function of compressing the image size when uploading.