h5图片压缩后变为base64格式的流地址上传服务器

**操作逻辑:前端把图片压缩变为base64格式的流地址,然后把base64格式的流地址传输到后端进行上传到cos服务器

操作流程**
1.前端:我这里是通过uniapp开发h5的,upLoadPutBase64是封装好的上传后端服务器的接口

复制代码
div写上
<helang-compress ref="helangCompress"></helang-compress>


引入压缩文件
	import helangCompress from '../../components/helang-compress/helang-compress';

// 单张压缩
					this.$refs.helangCompress.compress({
						src: filePath,
						maxSize: 800,
						fileType: 'jpg',
						quality: 0.85,
						minSize: 640 //最小压缩尺寸,图片尺寸小于该时值不压缩,非H5平台有效。若需要忽略该设置,可设置为一个极小的值,比如负数。
					}).then((res1) => {
						// 压缩成功回调
						// console.log('压缩成功回调', res1)
						upLoadPutBase64({ //发送请求给后端
							base64: res1
						}).then(resdata => {
							if (resdata.data.code == 200) {
								//更新信息
								undateUserInfo({
									avatar: resdata.data.url
								}).then(res => {
									if (res.data.code != 200) {
										return uni.$u.toast(res.data.message)
									}
									this.userInfo.avatar = resdata.data.url
									uni.setStorage({
										key: 'userInfo',
										data: JSON.stringify(this
											.userInfo),
									})
									uni.hideLoading();
									uni.$u.toast('上传成功');
								})
							} else {
								uni.hideLoading();
								uni.$u.toast('上传失败');
							}
						})
					}).catch((err) => {
						// 压缩失败回调
						uni.hideLoading();
						uni.$u.toast('上传失败');
					})

后端hyperf

复制代码
   //将Base64转为图片并保存到cos服务器
    #[RequestMapping(path: "putBase64", methods: ["POST"])]
    #[Middleware(middleware: UserJwtMiddleware::class)]
    public function putBase64(RequestInterface $request)
    {
        $file = $request->input('base64'); // 获取上传的文件
        $base64Prefix = 'data:image/jpeg;base64,';
        $base64Image = substr($file, strlen($base64Prefix));
        // 处理上传逻辑,保存文件到本地或其他操作
        // 示例:上传文件到 COS
        $cosObjectName = 'ultra/' . date('YmdHis') . '/' . uniqid() . '.png';
        $secretId = env('COS_SECRET_ID'); // 替换为你的 secretId
        $secretKey = env('COS_SECRET_KEY'); // 替换为你的 secretKey
        $region = env('COS_REGION'); // 替换为你的 COS 存储桶所在的地域
        // 初始化 COS 客户端
        $cosClient = new Client([
            'region' => $region, // COS 服务地域
            'schema' => 'https', // 协议头部,默认为 http
            'credentials' => [
                'secretId' => $secretId,
                'secretKey' => $secretKey
            ]
        ]);
        try {
            // 发起创建多部分上传请求
            $result = $cosClient->putObject(array(
                'Bucket' => env('COS_BUCKET_COS_APPID'), // 替换为你的 COS 存储桶名称,BucketName-Appid
                'Key' => $cosObjectName,   // 替换为你的对象名称,例如:test/example.jpg
                'Body' => base64_decode($base64Image),
            ));
            // 输出的结果为标准json格式
            return [
                'code' => 200,
                'message' => 'success',
                'url' => env('COS_DOMAIN') . '/' . $result['Key'],
            ];
            // print_r($result);
        } catch (\Exception $e) {
            // 输出请求失败时的异常信息
            // echo $e->getMessage();
            $logger = logger();
            $logger->debug('文件上传请求异常信息=', ['exception' => $e, 'uniqueId' => uniqid()]);
            return [
                'code' => 500,
                'message' => 'fail',
                'getMessage' => $e->getMessage(),
            ];
        }
    }
相关推荐
1001101_QIA4 小时前
工控机网络配置
开发语言·数据库·php
catchadmin4 小时前
对标 npx 的 CPX PHP 的 Composer 包执行器
开发语言·php·composer
狗凯之家源码网11 小时前
域名防红系统源码效果实测与能力边界解析
php
2601_9657984711 小时前
Why Most WordPress Themes Break Elementor and How I Fixed It
数据库·人工智能·php
郑州光合科技余经理17 小时前
代驾系统架构拆解:订单链路、权限组织与私有化源码交付
开发语言·后端·算法·架构·系统架构·uni-app·php
Ivanqhz1 天前
php8 use-def链
算法·php
大鹏说大话1 天前
HTML5 地理定位 Geolocation:获取用户位置的“红线”与最佳实践
前端·html·html5
DFT计算杂谈1 天前
ZrBr单层掺杂诱导的自旋/反常霍尔响应切换
linux·开发语言·机器学习·php·量子计算
冷咖啡离 我的笨笨1 天前
通过(Node Js||.Net)基于HTML5的WebSocket实现实时视频文字传输(上)
javascript·.net·html5
BingoGo1 天前
PHP 8.6 新特性一览
后端·php