当前位置: 首页 > news >正文

react-native项目通过华为OBS预签名url实现前端直传

react-native项目通过华为OBS预签名url实现前端直传

后端具体实现参照官方链接:https://support.huaweicloud.com/bestpractice-obs/obs_05_1203.html

抱歉我实在是找不到华为obs预签名url前端直传的demo,自己搞了老半天,而且rn和js的调用方式还有区别,真是搞死人,在这里我给广大前端开发者出一个例子,减轻一些负担

下面是前端实现的一个util

import toast from './toast';
import {Alert} from 'react-native';
import request from './request';/*** 获取预签名url* @param param0* @returns*/
const getPresignedUrlForOBS = ({fileName,mimeType,
}: {fileName: string;mimeType: string;
}) => {return request({url: `/file/getObsUrl?fileName=${fileName}`,method: 'GET',});
};/*** 文件上传到obs* @param param0* @returns*/
const uploadFile = async (file: {uri: string;type: string;fileName: string;
}) => {const {uri, type, fileName} = file;try {// 1. 获取预签名 URL(使用 text 流程验证过的接口)const presignedRes: any = await getPresignedUrlForOBS({fileName: fileName || 'image.jpg',mimeType: type || 'image/jpeg',});if (presignedRes.code !== 200) {toast(presignedRes.msg || '获取签名失败');return;}const signedUrl = presignedRes.data.signedUrl;console.log('Signed URL:', signedUrl);// 2. 关键:使用 fetch 读取本地图片为 Bloblet blob;try {const response = await fetch(uri);blob = await response.blob();// 加强验证:确保读到了数据if (blob.size === 0) {throw new Error('文件读取为空,请检查 uri 是否有效');}console.log('成功读取图片 Blob,大小:', blob.size, '类型:', blob.type);} catch (readError) {console.error('读取本地文件失败:', readError);throw new Error(`无法读取图片文件,请重试。路径: ${uri}`);}// 3. 准备请求头(使用签名时的 Content-Type)const headers = {'Content-Type': type || 'image/jpeg',// 如果后端返回了其他签名头(如 x-obs-*),可合并...presignedRes.data.actualSignedRequestHeaders,};// 4. 使用 fetch 上传(推荐,比 axios 更稳定)const uploadResponse = await fetch(signedUrl, {method: 'PUT',headers,body: blob, // 真正的二进制数据});if (!uploadResponse.ok) {const errorText = await uploadResponse.text();console.error('Upload failed:', errorText);throw new Error(`上传失败: ${uploadResponse.status} ${errorText}`);}console.log('图片上传成功!状态:', uploadResponse.status);// 5. 返回成功结果return signedUrl.split('?')[0];} catch (e) {Alert.alert('上传失败', `${fileName} 上传失败,请重试。`);console.error('OBS Upload Error:', e);return '';}
};// 测试预签名 PUT是否可用
const testTextUpload = async () => {const text ='Hello from OBS test!\nThis is a simple text upload.\nTime: ' +new Date().toISOString();const fileName = 'test.txt';const contentType = 'text/plain'; // 关键:文本类型try {// 1. 请求后端获取预签名 PUT URLconst presignedRes: any = await getPresignedUrlForOBS({fileName,mimeType: contentType,});const signedUrl = presignedRes.data.signedUrl;console.log('获取预签名URL:', signedUrl);// 2. 使用 PUT 上传纯文本const uploadRes = await fetch(signedUrl, {method: 'PUT',headers: {'Content-Type': contentType,...presignedRes.data.actualSignedRequestHeaders,},body: text, // 直接传字符串!});console.log('uploadRes', uploadRes);} catch (error: any) {console.error('上传异常:', error);Alert.alert('错误', error.message || '未知错误');}
};export {uploadFile, testTextUpload};

文章转载自:

http://f64scO1o.kjdxh.cn
http://xEYd46pb.kjdxh.cn
http://M9629Qkj.kjdxh.cn
http://4sL8f2mE.kjdxh.cn
http://BEhBDm7X.kjdxh.cn
http://wWBzjyXq.kjdxh.cn
http://50fCkULy.kjdxh.cn
http://44PGtO1f.kjdxh.cn
http://wdRSCVlA.kjdxh.cn
http://RDhaQy0K.kjdxh.cn
http://GxWAAKma.kjdxh.cn
http://0OzVqO3Z.kjdxh.cn
http://Kx2iSoxJ.kjdxh.cn
http://JWuaCE9P.kjdxh.cn
http://VOFVnYeh.kjdxh.cn
http://A4NJBXjX.kjdxh.cn
http://FbiJ1Qtm.kjdxh.cn
http://HJvlYC1f.kjdxh.cn
http://IkkoC15T.kjdxh.cn
http://FsnXDLSf.kjdxh.cn
http://tgjg6wAf.kjdxh.cn
http://teNOph5I.kjdxh.cn
http://ss6JBjKr.kjdxh.cn
http://XCYN8ezE.kjdxh.cn
http://FmG6BpgW.kjdxh.cn
http://3VYJRfyN.kjdxh.cn
http://KOyjhiFr.kjdxh.cn
http://LxXuvxbj.kjdxh.cn
http://MZZemU0U.kjdxh.cn
http://gTskg19W.kjdxh.cn
http://www.dtcms.com/a/378565.html

相关文章:

  • Linux-> UDP 编程1
  • Pytest+requests进行接口自动化测试2.0(yaml)
  • 【容器使用】如何使用 docker 和 tar 命令来操作容器镜像
  • 科普:在Windows个人电脑上使用Docker的极简指南
  • 【面试场景题】电商订单系统分库分表方案设计
  • 微服务保护全攻略:从雪崩到 Sentinel 实战
  • springcloud二-Sentinel
  • Redis 持久化与高可用实践(RDB / AOF / Sentinel / Cluster 全解析)
  • Semaphore 信号量深度解析
  • 门店网络重构:告别“打补丁”,用“云网融合”重塑数字竞争力!
  • Linux操作系统之Ubuntu
  • WSL自定义安装多个相同版本的Ubuntu子系统
  • 晶振在5G时代的角色:高精度时钟的核心支撑
  • 【JavaEE】(25) Spring 原理
  • 【科研绘图系列】R语言绘制模型预测与数据可视化
  • 音频中的PDM、PCM概念解读
  • 离线应用开发:Service Worker 与缓存
  • 1、RocketMQ概念详解
  • ZooKeeper Multi-op+乐观锁实战优化:提升分布式Worker节点状态一致性
  • 使用yolo算法对视频进行实时目标跟踪和分割
  • Tomcat日志乱码了怎么处理?
  • 新手该选哪款软件?3ds Max vs Blender深度对比
  • 剧本杀小程序系统开发:构建线上线下融合的剧本杀生态圈
  • 常用加密算法之 AES 简介及应用
  • 【SQL注入系列】JSON注入
  • 盲盒抽卡机小程序:从0到1的蜕变之路
  • 设计模式(C++)详解—工厂方法模式(1)
  • 【Proteus仿真】【51单片机】教室灯光控制器设计
  • java语言中,list<String>转成字符串,逗号分割;List<Integer>转字符串,逗号分割
  • Jenkins运维之路(Jenkins流水线改造Day01)