You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript上传Blob至Google Cloud Storage失败求助

使用JavaScript上传文件到Google Cloud Storage时出现400错误

我尝试通过JavaScript将文件上传至Google Cloud Storage,但一直失败,收到400 HTTP错误。以下是我的代码及问题细节:

完整上传代码

function uploadFile(){
    const file = document.querySelector('input[type=file]').files[0];
    const reader = new FileReader();
    let blob;
    reader.onload = function(e) {
        console.log(file)
        blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });

        fetch('https://storage.googleapis.com/upload/storage/v1/b/\"my_bucket_here\"/o', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer \"Token here\"'
            },
            body: blob,
        })
            .then(response => console.log('Success'))
            .catch(error => console.log(error));
    };
    reader.readAsArrayBuffer(file);
}

代码步骤说明

  • 从HTML文件输入框获取文件:
    const file = document.querySelector('input[type=file]').files[0];
    
    对应的HTML:
    <input type="file" id="upload" name="upload" class="box">
    
  • 通过FileReader将文件转换为Blob,控制台能正常打印选中的文件,这部分应该没问题。
  • 使用Fetch API上传Blob到存储桶时触发400错误,错误信息:
    POST https://storage.googleapis.com/upload/storage/v1/b/yaec_example/o 400
    reader.onload @ upload.js:11
    load (async)
    uploadFile @ upload.js:7
    onclick @ index.html?_ijt=v0tmlt6ecn7lbgsgmve0d34dra:49
    

问题修复方案

以下是几个关键的错误点和对应的修复方式:

1. 修正存储桶URL格式

你的Fetch URL中包含多余的转义引号\",正确的URL需要移除这些符号,同时必须添加uploadType=media参数(简单上传模式),并指定文件名:

fetch(`https://storage.googleapis.com/upload/storage/v1/b/my_bucket_here/o?uploadType=media&name=${encodeURIComponent(file.name)}`, {
  // 其他配置
})

2. 调整请求头与请求体

  • 移除Authorization头里Token前后的转义引号,确保令牌格式正确:'Authorization': 'Bearer Token here'
  • 无需将File转成Blob,直接使用原始file对象作为请求体即可,同时将Content-Type设置为文件本身的类型:
headers: {
  'Authorization': 'Bearer Token here',
  'Content-Type': file.type
},
body: file

3. 验证权限与令牌有效性

确保你的Bearer令牌拥有storage.objects.create权限,且令牌未过期。同时检查存储桶名称是否完全正确,存储桶的IAM权限是否允许该账号写入,以及是否配置了正确的跨域资源共享(CORS)规则。

内容的提问来源于stack exchange,提问作者Lukas.lmst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 19:05:21