export const uploadFile = async (params: {
file: any;
isLong: boolean;
name?: string;
filderName?: string;
formState?: any;
isRelative?: boolean;
}) => {
// info, type, formState, filderName,
return new Promise(async (resolve, reject) => {
try {
const { file } = params.file;
console.log(file, 'refiles');
const resFile = await compressorImage(file);
// console.log('res>>>>>', resFile);
const data = await getCommonUploadImage(params.isLong);
const signData = JSON.parse(JSON.stringify(data?.resultData));
const curFilename = file.name;
const { accessKeyId, bucketName, accessKeySecret, securityToken, fileName, fileUrl } =
signData;
const client = new OSS({
// 上传地址前缀
bucket: bucketName,
region: 'oss-cn-qingdao',
accessKeyId: accessKeyId,
accessKeySecret: accessKeySecret,
stsToken: securityToken,
});
// const timesStr = +new Date();
// 图片存贮位置
const storeAs = `${fileName}/${params.filderName}/${curFilename}`;
const headers = {
'Content-Type': 'image/jpg',
};
// 可预览图片完整地址:`${signData.fileUrl}/${storeAs}`
console.log('res压缩后img>>>>>', resFile);
client.put(storeAs, resFile, headers).then((res: any) => {
console.log(res, 'res');
resolve(params.isRelative ? res.name : `${fileUrl}/${res.name}`);
});
params.file.onSuccess({}, file);
} catch (e: any) {
// 全局打印报错
reject(e?.message);
createMessage.error(e?.message);
}
});
};
// 压缩文件
async function compressorImage(image: File) {
const file = image;
const maxSize = 1024 * 1024 * 6;
return new Promise((resolve) => {
compressImage(file, maxSize, 0.9, (comFile) => {
resolve(comFile);
});
});
}
/**
* @param image 图片
* @param maxSize 图片大小限制
* @param quality 图片压缩比 0-1,数字越小,图片压缩越小
* @param callback 获取压缩后的图片
* @returns
*/
function compressImage(curFile, maxSize, quality, callback) {
const reader = new FileReader();
reader.onload = function (event) {
const img: any = new Image();
img.src = event.target?.result;
img.onload = function () {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const width = img.width;
const height = img.height;
canvas.width = width;
canvas.height = height;
ctx?.drawImage(img, 0, 0, width, height);
canvas.toBlob(
function (blob: any) {
const file = new window.File([blob], curFile.name, { type: blob.type });
if (curFile?.size > maxSize) {
if (quality > 0.1) {
compressImage(file, maxSize, quality - 0.1, callback);
} else {
// 实在压不动了
callback(file);
}
} else {
callback(file);
}
},
'image/jpeg',
quality,
);
};
};
reader.readAsDataURL(curFile);
}
上传压缩图片(案例:oss)
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 预览图片,FileReader,可以读取File和Blob对象,并转为base64格式的图片 预览图片,URL.c...
- 引入一个js: 百度网盘链接:https://pan.baidu.com/s/1KO9gH4r6bP-foYVAQ...
- 作者是在vue上做的开发,可能对有学过vue学者比较友好 首先,我们看看整个执行过程的类型转换 input -->...
- 第一次做上传剪裁图片,找了许多框架,最后找到一个优雅的图片裁剪插件vue-cropper,很方便新手入手 安装 n...