H5图片单张、多张上传逻辑封装,图片压缩

页面组件中的代码

html代码(使用vant 组件库文件上传)
   <van-field label="照片" required :rules="[{ validator: validatorImg }]">
      <template #input>
        <van-uploader
          v-model="question.fileList"
          capture="camera"
          :max-count="imgMaxNum"
          :before-read="beforeRead"
          @click-upload="imgStr = 'fileList'"
          @delete="onDelete"
          multiple
        />
      </template>
    </van-field>
js代码
import { useUpdateFile} from '@/hooks/useUpdateImg';
const { compressPicture, onDelete } = useUpdateFile();
// 添加图片
const validatorImg = (val) => (val.length ? true : "请上传图片");
const imgMaxNum = ref(4)
const imgStr = ref()
const question = reactive({})

const beforeRead= (file) => {
	try {
	 	question[imgStr.value] = question[imgStr.value] || [];
        const res =await compressPicture(file, imgMaxNum, question[imgStr.value].length).then(res=>{
	   	    question[imgStr.value] = question[imgStr.value].concat(res);
        })
    } catch (err) {
    	console.log(err)
    }
};
/**
*注:question为数组时的代码思路
*const idx= ref(0)
* @click-upload="()=>{imgStr = 'fileList',idx=index}"
*question.value[idx.value][imgStr.value] =question.value[idx.value][imgStr.value]||[]
 question.value[idx.value][imgStr.value].push(res);
*/

src/hooks/useUpdateImg.js (文件创建路径)

pnpm i image-conversion  
// 安装图片压缩所需要的依赖包
import * as imageConversion from "image-conversion"
import { uploadImg, delFile } from "@/api";
import { showLoadingToast, closeToast, showToast, showNotify } from "vant";
export function useUpdateFile() {
    const prefix = '获取图片资源的前缀,自行替换'
    // 压缩图片
    const compressPicture = (file, maxNum = 2, nowNum) => {
        const compressApis = []
        const num = maxNum - nowNum  (计算出剩余的图片上传数量)
        file = Object.prototype.toString.call(file) == '[object Array]' ? file.slice(0, num) : [file]
        return new Promise((resolve) => {
            showLoadingToast({
                message: "正在压缩...",
                forbidClick: true,
                duration: 0,
            });
            file.forEach((file) => {
                compressApis.push(
                    new Promise((resolve) => {
                        imageConversion.compressAccurately(file, 1024).then(res => {
                            let afterFile
                            if (file.size > 1024 * 1024 * 1) {
                                afterFile = new File([res], "0.jpg")
                            } else {
                                afterFile = file
                            }
                            resolve(afterFile)
                        })
                    })
                )
            })
            Promise.all(compressApis).then((res) => {
                closeToast();
                let data = new FormData();
                res.forEach((item) => { data.append("file", item) })
                uploadImg(data).then((res) => {
                    if (res.status === 200) {
                        showToast("上传成功");
                        const result = res.data.split(',')
                        const imgList = result.map(v => {
                            return {
                                url: `${prefix}${v}`,
                                name: v
                            }
                        })
                        resolve(imgList)
                    } else {
                        showNotify({ type: 'warning', message: '图片上传失败' })
                    }
                });
            })
        })

    };
    // 删除图片
    const onDelete = (file) => {
        delFile(file.name).then((res) => {
            res.status === 200 && showToast("删除成功");
        });
    };
    // 照片回显处理(编辑页也以此回显)
    const imgDispose = (str) => {
        if (!str) return []
        const fileList = [];
        str.split(",").forEach((val) => {
            fileList.push({
                name: val,
                url: `${prefix}${val}`,
            });
        });
        return fileList
    };
    return { prefix, compressPicture, onDelete, imgDispose };
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值