网上搜不到合适的例子,所以写了一个,感觉应该有一些参考价值,核心就是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做了一个简单的图片尺寸压缩,如需其他处理可以自行添加。(网上压缩图片的例子很多)
希望能帮助到更多的人。