ckeditor4 上传图片压缩 图片压缩后上传 上传文件前处理 上传图片之前压缩图片

网上搜不到合适的例子,所以写了一个,感觉应该有一些参考价值,核心就是ckeditor中的一个属性:fileUploadRequest

下面看例子

const questionBodyEditor = CKEDITOR.replace( 'questionBodyEditor');

questionBodyEditor.on( 'fileUploadRequest', function( evt ) {
    var fileLoader = evt.data.fileLoader,
        formData = new FormData(),
        xhr = fileLoader.xhr;
    xhr.open( 'POST', fileLoader.uploadUrl, true );
    const imageCom = new Image();
    imageCom.src = fileLoader.data;
    imageCom.onload = function() {
        //尺寸阈值
        const threshold = 1000;
        let w = imageCom.width;
        let h = imageCom.height;
        if(w > threshold && h > threshold){
            h = threshold * h / w;
            w = threshold;
        }
        let canvas = document.createElement('canvas'),
            context = canvas.getContext('2d'),
            imageWidth = w,    //压缩后图片的大小
            imageHeight = h,
            data = ''

        canvas.width = imageWidth;
        canvas.height = imageHeight;
        context.drawImage(imageCom, 0, 0, imageWidth, imageHeight)
        data = canvas.toDataURL('image/jpeg');
        data = dataURLtoFile(data)
        //压缩完成
        formData.append( 'upload', data, fileLoader.fileName );
        fileLoader.xhr.send( formData );
    }
    evt.stop();
} );

//图片转化
function dataURLtoFile(dataurl, filename = 'file') {
    let arr = dataurl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let suffix = mime.split('/')[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
    })
}

上传图片接口传参较为特殊,不能直接ajax,所以用了原生xhr.send。

中间我是用了canvas做了一个简单的图片尺寸压缩,如需其他处理可以自行添加。(网上压缩图片的例子很多)

希望能帮助到更多的人。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值