0Pricing
Supabase Backend as a Service · บทเรียน

การอัปโหลดและดึงสื่อ

ฝึกอัปโหลดรูปภาพ วิดีโอ และไฟล์สื่ออื่น ๆ จากนั้นดึงไฟล์เหล่านั้นมาแสดงในแอปพลิเคชัน

การอัปโหลดและดึงสื่อ เป็นบทเรียน Supabase Backend as a Service ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Supabase Backend as a Service และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Supabase Backend as a Service มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Media for Dynamic Apps

User avatars, product images, videos – media makes applications rich and engaging. Learning to manage files effectively is crucial for modern app development.

In this lesson, we'll focus on using the Supabase Storage client to upload various media types and retrieve them for display.

The Supabase Storage Client

The supabase.storage client is your gateway to interacting with file storage. It allows you to perform operations like uploading, downloading, and managing files within your Supabase buckets.

You'll typically initialize your Supabase client once in your application.

Preparing Files for Upload

Before you can upload a file, you need its data. In web applications, this often comes from an HTML <input type="file"> element, giving you a File or Blob object.

For our examples, we'll simulate a Blob object to represent file data, making the code runnable.

Uploading Your First File

Use the upload() method to send a file to a specific bucket path. You'll need to specify the bucket name, the desired file path (including the filename), and the file's data.

Try running this example to see a simulated file upload:

// Assume 'createClient' is imported from '@supabase/supabase-js'
// Assume 'SUPABASE_URL' and 'SUPABASE_ANON_KEY' are configured

const createClient = (url, key) => ({
  storage: {
    from: (bucketName) => ({
      upload: async (filePath, fileData, options) => {
        console.log(`[MOCK] Uploading to bucket '${bucketName}', path '${filePath}'`);
        console.log(`[MOCK] File data type: ${fileData.type}, size: ${fileData.size}`);
        console.log(`[MOCK] Options: ${JSON.stringify(options)}`);
        return { data: { path: filePath, id: 'mock-id' }, error: null };
      }
    })
  }
});

const SUPABASE_URL = 'https://your-project.supabase.co'; // Replace with your URL
const SUPABASE_ANON_KEY = 'YOUR_ANON_KEY'; // Replace with your Anon Key
const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);

async function uploadExample() {
  const fileData = new Blob(['Hello CoddyKit!'], { type: 'text/plain' });
  const fileName = 'lesson-note.txt';
  const filePath = `public/${fileName}`; // Store in a 'public' folder

  try {
    const { data, error } = await supabase
      .storage
      .from('my-bucket') // Use your actual bucket name
      .upload(filePath, fileData, {
        cacheControl: '3600', // Cache for 1 hour
        upsert: false // Do not overwrite if file exists
      });

    if (error) {
      throw error;
    }
    console.log('Upload successful:', data);
  } catch (error) {
    console.error('Error uploading file:', error.message);
  }
}

uploadExample();

Understanding Upload Options

The upload() method accepts an options object to fine-tune the upload process:

  • cacheControl: Sets the Cache-Control header, telling browsers how long to cache the file.
  • upsert: A boolean. If true, an existing file at the specified path will be overwritten. If false (default), it will error if the file exists.
  • contentType: The MIME type of the file (e.g., 'image/jpeg'). Often inferred, but good to set explicitly for accuracy.

Retrieving Public URLs

For files stored in buckets with public access (configured via Storage Policies), you can get a direct, publicly accessible URL. This URL can be used in <img> tags, <video> tags, or as direct download links.

The getPublicUrl() method will give you this link.

// Assume 'createClient' is imported and configured
const createClient = (url, key) => ({
  storage: {
    from: (bucketName) => ({
      getPublicUrl: (filePath) => {
        console.log(`[MOCK] Getting public URL for bucket '${bucketName}', path '${filePath}'`);
        return { data: { publicUrl: `https://mock.supabase.co/storage/v1/object/public/${bucketName}/${filePath}` } };
      }
    })
  }
});

const SUPABASE_URL = 'https://your-project.supabase.co';
const SUPABASE_ANON_KEY = 'YOUR_ANON_KEY';
const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);

function getPublicUrlExample() {
  const filePath = 'public/lesson-note.txt'; // Path of your uploaded file
  const { data } = supabase
    .storage
    .from('my-bucket') // Use your actual bucket name
    .getPublicUrl(filePath);

  console.log('Public URL:', data.publicUrl);
}

getPublicUrlExample();

Displaying Media in Your App

Once you have the public URL from getPublicUrl(), displaying media in your application is straightforward. You simply use the URL in the appropriate HTML element's src attribute.

  • Images: <img src="YOUR_PUBLIC_URL" alt="description">
  • Videos: <video src="YOUR_PUBLIC_URL" controls></video>
  • Audio: <audio src="YOUR_PUBLIC_URL" controls></audio>

Securely Accessing Private Media

Not all files should be publicly accessible. For private files (e.g., user documents, sensitive media) protected by RLS policies, you can't use a simple public URL.

Supabase provides signed URLs for secure, temporary access to these private files. These URLs include a temporary token that expires after a set duration.

Generating Signed URLs

The createSignedUrl() method generates a temporary URL for a private file. You specify the file path and how long (in seconds) the URL should be valid.

This is ideal for scenarios where you want to grant authenticated users temporary access to private content without making it globally public.

// Assume 'createClient' is imported and configured
const createClient = (url, key) => ({
  storage: {
    from: (bucketName) => ({
      createSignedUrl: async (filePath, expiresIn) => {
        console.log(`[MOCK] Creating signed URL for bucket '${bucketName}', path '${filePath}', expires in ${expiresIn}s`);
        return { data: { signedUrl: `https://mock.supabase.co/storage/v1/object/sign/${bucketName}/${filePath}?token=mock-token&expires=${expiresIn}` }, error: null };
      }
    })
  }
});

const SUPABASE_URL = 'https://your-project.supabase.co';
const SUPABASE_ANON_KEY = 'YOUR_ANON_KEY';
const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);

async function getSignedUrlExample() {
  const privateFilePath = 'private/user-report.pdf'; // Path to a private file
  const expiresInSeconds = 60; // URL valid for 60 seconds

  try {
    const { data, error } = await supabase
      .storage
      .from('my-private-bucket') // Use your actual private bucket name
      .createSignedUrl(privateFilePath, expiresInSeconds);

    if (error) {
      throw error;
    }
    console.log('Signed URL:', data.signedUrl);
    console.log(`This URL will expire in ${expiresInSeconds} seconds.`);
  } catch (error) {
    console.error('Error creating signed URL:', error.message);
  }
}

getSignedUrlExample();

Upload & Retrieve Check

Let's test your understanding of uploading and retrieving media with Supabase Storage.

Media Management Mastered

You've successfully learned how to:

  • Upload files to Supabase Storage buckets using upload().
  • Retrieve public URLs for immediate display with getPublicUrl().
  • Generate secure, time-limited signed URLs for private content using createSignedUrl().

These skills are fundamental for building rich, dynamic applications that handle user-generated content or managed media assets securely and efficiently.

คำถามที่พบบ่อย

บทเรียน “การอัปโหลดและดึงสื่อ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การอัปโหลดและดึงสื่อ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Supabase Backend as a Service ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Supabase Backend as a Service มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การอัปโหลดและดึงสื่อ”

ฝึกอัปโหลดรูปภาพ วิดีโอ และไฟล์สื่ออื่น ๆ จากนั้นดึงไฟล์เหล่านั้นมาแสดงในแอปพลิเคชัน คุณปฏิบัติ Supabase Backend as a Service ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Supabase Backend as a Service หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Supabase Backend as a Service บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การอัปโหลดและดึงสื่อ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Supabase Backend as a Service นี้ได้ไหม

ได้ บทเรียน Supabase Backend as a Service ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การจัดเก็บไฟล์ในบักเก็ตของ Supabase
  2. การจัดการการเข้าถึงด้วยนโยบาย
  3. การอัปโหลดและดึงสื่อ
  4. การแปลงรูปภาพและ URL แบบลงลายเซ็น
← กลับไปที่ Supabase Backend as a Service