미디어 업로드와 가져오기
이미지, 동영상 및 기타 미디어 파일을 업로드한 다음 애플리케이션에 표시하기 위해 가져오는 방법을 연습합니다.
미디어 업로드와 가져오기은(는) CoddyKit의 무료 Supabase Backend as a Service 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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 theCache-Controlheader, telling browsers how long to cache the file.upsert: A boolean. Iftrue, an existing file at the specified path will be overwritten. Iffalse(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.
자주 묻는 질문
“미디어 업로드와 가져오기” 강의는 무료인가요?
네 — “미디어 업로드와 가져오기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Supabase Backend as a Service 강의 전체를 잠금 해제할 수 있습니다. Supabase Backend as a Service 강의에는 총 4개의 강의가 포함되어 있습니다.
“미디어 업로드와 가져오기”에서 뭘 배우나요?
이미지, 동영상 및 기타 미디어 파일을 업로드한 다음 애플리케이션에 표시하기 위해 가져오는 방법을 연습합니다. 브라우저에서 직접 실행하는 실습 코드로 Supabase Backend as a Service을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Supabase Backend as a Service을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Supabase Backend as a Service은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“미디어 업로드와 가져오기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Supabase Backend as a Service 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Supabase Backend as a Service 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Supabase 버킷에 파일 저장
- 정책으로 접근 권한 관리
- 미디어 업로드와 가져오기
- 이미지 변환과 서명된 URL