Gemini API调用报错400:无效/不支持文件URI问题求助
Gemini API调用返回"Invalid or unsupported file uri"错误排查与解决
问题背景
使用无代码平台开发Android应用,因平台功能不足,嵌入HTML页面调用Gemini API传入图片求解数学题,但持续返回400错误,提示"Invalid or unsupported file uri"。已完成Google Cloud Console配置、启用计费、设置图片公开URL,问题仍未解决。
错误信息
{"error": {"code": 400, "message": "Invalid or unsupported file uri: https://storage.googleapis.com/BUCKETNAME/IMAGEFILE.jpg", "status": "INVALID_ARGUMENT"}}
相关代码
<!DOCTYPE html> <html> <head> <title>Gemini API Image Upload</title> </head> <body> <h1>Upload Image URL to Gemini API</h1> <input type="text" id="imageUrlInput" placeholder="Enter public image URL"> <button id="uploadButton">Submit</button> <div id="responseArea"></div> <script> const apiKey = 'api key is here'; const imageUrlInput = document.getElementById('imageUrlInput'); const uploadButton = document.getElementById('uploadButton'); const responseArea = document.getElementById('responseArea'); async function sendImageToGemini(imageUrl) { const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro-latest:generateContent?key=${apiKey}`; const payload = { "contents": [ { "role": "user", "parts": [ { "fileData": { "fileUri": imageUrl, "mimeType": "image/jpeg" } }, { "text": "Please solve this mathematics question" } ] } ], "generationConfig": { "temperature": 1, "topK": 64, "topP": 0.95, "maxOutputTokens": 8192, "responseMimeType": "text/plain" } }; try { const response = await fetch(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); const data = await response.json(); responseArea.innerHTML = `<h3>Response:</h3><pre>${JSON.stringify(data, null, 2)}</pre>`; } catch (error) { console.error('Error:', error); responseArea.innerHTML = `<h3>Error:</h3><pre>${error}</pre>`; } } uploadButton.addEventListener('click', () => { const imageUrl = imageUrlInput.value; if (imageUrl) { sendImageToGemini(imageUrl); } else { alert('Please enter a public image URL first.'); } }); </script> </body> </html>
解决方法
核心原因
使用fileData字段时,Gemini API要求文件URI必须是Google Cloud Storage (GCS)的gs://格式路径,而非HTTP/HTTPS URL。代码中传入的https://storage.googleapis.com/...格式不符合API要求,导致报错。
修复步骤
- 修改URI格式:将Payload中的
fileUri值从HTTPS格式改为gs://BUCKETNAME/IMAGEFILE.jpg。 - 验证GCS权限:确保GCS存储桶和文件允许Gemini API访问:
- 给存储桶添加IAM权限,授予
roles/storage.objectViewer角色给generativelanguage@googleapis.com服务账号; - 或确保文件已设置公开访问权限(不推荐生产环境使用)。
- 给存储桶添加IAM权限,授予
修改后的Payload核心片段
const payload = { "contents": [ { "role": "user", "parts": [ { "fileData": { "fileUri": "gs://BUCKETNAME/IMAGEFILE.jpg", // 改为gs://格式 "mimeType": "image/jpeg" } }, { "text": "Please solve this mathematics question" } ] } ], // 其他配置保持不变 };
替代方案(无需GCS)
若不想依赖GCS,可将图片转为Base64编码直接嵌入请求:
// 图片转Base64函数 async function getImageBase64(url) { const response = await fetch(url); const blob = await response.blob(); return new Promise((resolve) => { const reader = new FileReader(); reader.onloadend = () => resolve(reader.result.split(',')[1]); reader.readAsDataURL(blob); }); } // 修改请求函数 async function sendImageToGemini(imageUrl) { const base64Image = await getImageBase64(imageUrl); const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro-latest:generateContent?key=${apiKey}`; const payload = { "contents": [ { "role": "user", "parts": [ { "inlineData": { "data": base64Image, "mimeType": "image/jpeg" } }, { "text": "Please solve this mathematics question" } ] } ], // 其他配置保持不变 }; // 后续请求逻辑不变 }
内容的提问来源于stack exchange,提问作者Varun Kadapatti
相关产品推荐
相关产品推荐

