如何使用React更新/覆盖GCS中的JSON元数据
谷歌云存储对象元数据更新方案及问题修复
背景
我研究了谷歌云存储对象元数据的编辑方法,找到对应的curl命令:
curl -X PATCH --data-binary @JSON_FILE_NAME \ -H "Authorization: Bearer OAUTH2_TOKEN" \ -H "Content-Type: application/json" \ "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME"
随后编写了React方法,预期将元数据中的id字段更新为newId:
updateMetadata = (bucketname,filename,newId) => { const { token } = this.props; return fetch('https://storage.googleapis.com/storage/v1/b/bucketname/o/filename', { 'method': 'PATCH', 'headers': new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': token }), 'body': JSON.stringify({ 'metadata': { 'id': newId } }) }) .then( response => {return response.json()}) .then( res => { return res }) }
我对new FormData()的使用并不熟悉,参考的官方文档核心内容翻译如下:
前提条件(REST方式编辑元数据)
- 需持有目标存储对象的
storage.objects.update权限;- 已获取有效的OAuth2访问令牌,或使用服务账号密钥完成身份验证;
- 请求必须使用
PATCH方法,且请求体为JSON格式,仅包含需更新的元数据字段。
代码问题修复
你的React方法存在两处关键错误,修正后的代码如下:
updateMetadata = (bucketname, filename, newId) => { const { token } = this.props; // 替换URL中的硬编码参数,对文件名编码避免特殊字符问题 const requestUrl = `https://storage.googleapis.com/storage/v1/b/${bucketname}/o/${encodeURIComponent(filename)}`; return fetch(requestUrl, { method: 'PATCH', headers: new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json', // 补充Bearer前缀,与curl命令的认证格式保持一致 'Authorization': `Bearer ${token}` }), body: JSON.stringify({ metadata: { id: newId } }) }) .then(response => response.json()) .then(res => res); }
关键说明
- 无需使用
new FormData():该接口要求JSON格式请求体,与curl命令中Content-Type: application/json的要求匹配; - 文件名编码:使用
encodeURIComponent处理文件名,避免空格、特殊字符导致的请求路径错误; - 认证格式:Authorization头必须以
Bearer开头,这是OAuth2令牌的标准认证格式。
内容的提问来源于stack exchange,提问作者Oashi
相关产品推荐
相关产品推荐

