h5端 uni-app用户上传图片,超过限制则压缩图片

本文主要才用input type = file上传文件,在change事件中做出处理

  handleFileChange(event) {
        var imgfile = document.querySelector('#uploadInput');
        const file = event.target.files[0];
        //本次要求是超过3M进行图片压缩,不超过3M则正常上传
        if (file.size > 3 * 1024 * 1024) {
            const reader = new FileReader();
            reader.onload = () => {
                const img = new Image();
                img.src = reader.result;
                img.onload = () => {
                    const maxWidth = 800; // 设置最大宽度
                    const maxHeight = 800; // 设置最大高度

                    let width = img.width;
                    let height = img.height;

                    // 根据图片尺寸动态计算压缩后的尺寸
                    if (width > height && width > maxWidth) {
                        height *= maxWidth / width;
                        width = maxWidth;
                    } else if (height > maxWidth) {
                        width *= maxHeight / height;
                        height = maxHeight;
                    }

                    const canvas = document.createElement('canvas');
                    canvas.width = width;
                    canvas.height = height;

                    const ctx = canvas.getContext('2d');
                    ctx.drawImage(img, 0, 0, width, height); 

                    // 将 canvas 中的图片数据转换为 Base64 编码
                    const compressedBase64 = canvas.toDataURL('image/jpeg', 0.7); // 压缩质量为0.7,可根据需求调整

                    // 调用上传方法传输压缩后的 Base64 编码图片
                    emits('change', compressedBase64);
                };
            };
            reader.readAsDataURL(file);
        } else {
            const reader = new FileReader();
            reader.onload = () => {
                //这是个组件中的方法,这一步可以得到图片的base64地址,在父组件中可以用@change事件获取到地址结果 ,将其传送给后端,如果想要在单个文件中使用可以直接将reader.result直接传递给后端
                emits('change', reader.result);
                document.body.removeChild(data.filePicker);
            };
            reader.readAsDataURL(file);
        }
    },

完整的代码

<template>
    <view>
        <div class="taskcls">
            <div class="imgbox1">
                <div v-for="(value, key) in photoList" :key="key" class="imgbox">
                    <img class="imgsss" :src="value" id="uploadImg" />
                    <div class="close" @click="methods.delImg(value)">
                        <img src="@/static/svg/chacha.svg" alt="">
                    </div>
                </div>
            </div>
            <input ref="file" type="file" id="file" accept="image/*" @change="methods.handleFileChange" multiple
                style="display:none" />
            <div class="positive" @click="methods.zhengmian" v-if="photoList.length < 3">
                <div class="imgsss">
                    <img src="@/static/svg/jiahao.svg" alt="">
                </div>
            </div>

        </div>
    </view>
</template>

<script setup >
import { ArrayProp } from '../composables/useProps';
import { Toast } from '@/utils/uniapi/prompt';


const data = reactive({
    filePicker: null
})

const props = defineProps({
    photoList: ArrayProp,
});
const emits = defineEmits(['change']);

const methods = {
    // 假的上传框,点击的时候生成上传文件类型的input并点击
    zhengmian() {
        data.filePicker = document.createElement('input')
        data.filePicker.id = 'uploadInput'
        data.filePicker.type = 'file'
        // filePicker.accept = 'image/png, image/jpeg, image/jpg,image/gif,image/webp'
        data.filePicker.accept = 'image/*'
        data.filePicker.style.display = 'none'
        data.filePicker.addEventListener('change', methods.handleFileChange)
        document.body.appendChild(data.filePicker)
        data.filePicker.click()
        // filePicker = null
    },
    // 上传现场照片,将图片存到form中
    handleFileChange(event) {
        var imgfile = document.querySelector('#uploadInput');
        const file = event.target.files[0];

        if (file.size > 3 * 1024 * 1024) {
            const reader = new FileReader();
            reader.onload = () => {
                const img = new Image();
                img.src = reader.result;
                img.onload = () => {
                    const maxWidth = 800; // 设置最大宽度
                    const maxHeight = 800; // 设置最大高度

                    let width = img.width;
                    let height = img.height;

                    // 根据图片尺寸动态计算压缩后的尺寸
                    if (width > height && width > maxWidth) {
                        height *= maxWidth / width;
                        width = maxWidth;
                    } else if (height > maxWidth) {
                        width *= maxHeight / height;
                        height = maxHeight;
                    }

                    const canvas = document.createElement('canvas');
                    canvas.width = width;
                    canvas.height = height;

                    const ctx = canvas.getContext('2d');
                    ctx.drawImage(img, 0, 0, width, height);

                    // 将 canvas 中的图片数据转换为 Base64 编码
                    const compressedBase64 = canvas.toDataURL('image/jpeg', 0.7); // 压缩质量为0.7,可根据需求调整

                    // 调用上传方法传输压缩后的 Base64 编码图片
                    emits('change', compressedBase64);
                };
            };
            reader.readAsDataURL(file);
        } else {
            const reader = new FileReader();
            reader.onload = () => {
                emits('change', reader.result);
                document.body.removeChild(data.filePicker);
            };
            reader.readAsDataURL(file);
        }
    },


    //点击删除按钮,从form中移除
    delImg(val) {
        const index = props.photoList.findIndex((item) => item === val);
        props.photoList.splice(index, 1);
    },

}





</script>

<style lang="scss" >
.taskcls {
    display: flex;
}

.taskcls-a {
    width: 25%;
    line-height: 44px;
    color: #b4b4b4ff;
    font-size: 14px;
    margin-left: 10px;
}

.taskcls-b {
    width: 80%;
}

.taskcls-c {
    /* margin-left: -20px; */
}

.btn {
    width: 100%;
}

.positive {
    width: 99px;
    height: 99px;
    /* border: 1px solid red; */
    position: relative;
    float: left;
    margin-left: 5px;
    margin-top: 5px;
    display: inline-block;
}

.imgbox {
    position: relative;
    display: inline-block;
}

.imgsss {
    display: inline-block;
    width: 99px;
    height: 99px;
    line-height: 99px;
    background: #f8f9fdff;
    border-radius: 5px;
    position: relative;
    margin: 5px;
    text-align: center;
}

.imgsss img {
    width: 20px;
    height: 20px;

}

.close img {
    width: 20px;
    height: 20px;
    color: gray;
    position: absolute;
    right: 0;
    top: 0;

}
</style>

实现效果

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值