Supabase Bucket getPublicUrl返回无效URL问题求助
Fix: "Object Not Found" When Accessing Supabase Public Storage URLs
The core issue in your code is using listBuckets() to retrieve files—this method returns all buckets in your project, not the files inside a specific bucket. When you iterate over the result, you're working with bucket objects instead of file objects, leading to invalid file names in your public URLs.
Corrected Code for Fetching Files
Replace listBuckets() with list() to get the files within your target bucket. Also, handle async operations properly (since map with async functions requires Promise.all):
// Fetch files inside the specific bucket const { data: filesList, error } = await supabase.storage .from(order.bucketId) .list(); // Use list() instead of listBuckets() if (error) { console.error('Error fetching files:', error); return; } // Generate public URLs for each file const files = await Promise.all(filesList.map(async (file) => { const { data: publicUrlData, error: urlError } = supabase.storage .from(order.bucketId) .getPublicUrl(file.name); if (urlError) { console.error('Error getting public URL:', urlError); return null; } return publicUrlData.publicUrl; })); // Filter out any null entries from errors const validUrls = files.filter(url => url !== null);
Additional Checks to Ensure Access
- Verify Bucket Name: Confirm
order.bucketIdexactly matches thebucketNameyou used when creating the bucket and uploading files (Supabase bucket names are case-sensitive). - Check File Names: Ensure the
file.namevalues fromlist()match the filenames you used during upload (no extra spaces, typos, or case mismatches). - Validate Bucket Policies: Even for public buckets, double-check your storage policies. For a public bucket, your policy should allow read access to everyone:
CREATE POLICY "Public access for all files" ON storage.objects FOR SELECT USING (bucket_id = 'your-bucket-name'); - Test Direct URL: Manually construct the public URL using your project's storage endpoint to confirm it works:
https://<project-ref>.supabase.co/storage/v1/object/public/<bucket-name>/<file-name>
内容的提问来源于stack exchange,提问作者alexgarciaalcuadrado
相关产品推荐
相关产品推荐

