imageConversion图片压缩后blob格式,formData上传需要拼接图片名称

本文介绍了在Vue项目中如何使用imageConversion模块进行图片压缩,并解决blob格式图片在formData上传时需拼接文件名的问题。重点在于压缩策略调整和formData正确添加文件名以避免服务器端错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 .https://blog.youkuaiyun.com/Superman_peng/article/details/107740407
1.安装模块

npm i image-conversion --save

2.引入imageConversion,进行压缩

const imageConversion = require("image-conversion");

3.实现

1》压缩到指定大小

//把图片文件作为参数传递到方法中
beforeAvatarUpload(file) {
	console.log(file)
	const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
		const isLt2M = file.size / 1024 / 1024 < 2;
		if (!isJpgOrPng) {
			this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
			return false;
		}
		if (!isLt2M) {
			this.$message.error('上传头像图片大小不能超过 2MB!');
			return false;
		}
		return new Promise((resolve) => {
			// 压缩到100KB,这里的100就是要压缩的大小,可自定义
			imageConversion.compressAccurately(file, 100).then(res => {
				console.log(res)
				resolve(res);
			});
            //compressAccurately有多个参数时传入对象
            //imageConversion.compressAccurately(file, {
                  // size: 1024, //图片大小压缩到1024kb
                  // width:1280 //宽度压缩到1280
       		//}).then(res => {
         			//resolve(res)
       		//})
		})
	},


2》按照一定质量倍数进行压缩

以质量为0.6进行压缩

//把图片文件作为参数传递到方法中
beforeAvatarUpload(file) {
	console.log(file)
	const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
		const isLt2M = file.size / 1024 / 1024 < 2;
		if (!isJpgOrPng) {
			this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
			return false;
		}
		if (!isLt2M) {
			this.$message.error('上传头像图片大小不能超过 2MB!');
			return false;
		}
		return new Promise((resolve) => {
			imageConversion.compress(file,0.6).then(res=>{
			    console.log(res);
			    resolve(res);
		    })
	    }
	},

二.压缩后格式是blob格式,formData上传到服务器时需要拼接图片名称,否则会出现所有上传的图片名称都为blob。
这里有个坑,那就是 FormData.append(‘file’, file),如果只有两个参数,(第三个参数是文件名)的情况下,默认fileName=“blob”,这样上次至后台,如果后台未做其他处理的话,就会出现报错的情况,后来就添加了随机文件名,完美解决问题。

 image.append("file", file, this.random_string(12) + '.' + this.fileType);

详细如下:
https://www.cnblogs.com/milo-wjh/p/9260276.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值