0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · 강의

액션을 활용한 파일 업로드

안전한 저장과 처리를 포함하여 Server Actions를 통해 파일 업로드를 직접 처리하는 방법을 배웁니다.

액션을 활용한 파일 업로드은(는) CoddyKit의 무료 Next.js 15 Fullstack (App Router + Server Actions) 강의입니다. 이것은 3개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Next.js 15 Fullstack (App Router + Server Actions) 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 3개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Uploading Files with Actions

File uploads are a common feature, allowing users to share images, documents, and more. Traditionally, handling these required complex API routes and separate handlers.

With Next.js Server Actions, handling file uploads becomes much simpler and more integrated directly within your forms, keeping your logic co-located.

Setting Up the File Input

To allow file uploads, you need an HTML form with a specific setup. The <input type="file"> element is essential for selecting files from a user's device.

  • Use the name attribute to identify the file in your Server Action.
  • Add enctype="multipart/form-data" to your <form> tag. This tells the browser to encode the form data, including files, correctly.
<form action="/api/upload" method="POST" enctype="multipart/form-data">
  <input type="file" name="myFile" />
  <button type="submit">Upload</button>
</form>

Capturing Files via FormData

When a form with enctype="multipart/form-data" is submitted to a Server Action, Next.js automatically parses the data into a FormData object.

You can access the uploaded file(s) from this FormData object using its get() method, which returns a standard JavaScript File object.

// app/actions.js
'use server';

export async function uploadFile(formData) {
  const file = formData.get('myFile');
  if (!file) {
    return { error: 'No file uploaded.' };
  }
  // 'file' is a File object
  console.log('File name:', file.name);
  console.log('File size:', file.size, 'bytes');
  console.log('File type:', file.type);
  return { success: true };
}

Exploring the File Object

The File object received in your Server Action is a powerful Web API object. It provides key information about the uploaded file:

  • name: The original filename provided by the user.
  • size: The file size in bytes.
  • type: The MIME type of the file (e.g., "image/jpeg", "application/pdf").
  • arrayBuffer(): An asynchronous method to get the file's content as an ArrayBuffer, which is crucial for saving it.

Storing Uploaded Files to Disk

To save the uploaded file permanently, you'll need to extract its content from the File object and write it to a storage location. The arrayBuffer() method helps convert the file into raw binary data.

You can then use Node.js's built-in fs/promises module to write this data to your server's file system.

// app/actions.js (continued)
'use server';
import { writeFile } from 'fs/promises';
import path from 'path';

export async function saveUploadedFile(formData) {
  const file = formData.get('myFile');
  if (!file || file.size === 0) return { error: 'No file.' };

  const buffer = Buffer.from(await file.arrayBuffer());
  const filename = Date.now() + '-' + file.name; // Unique filename
  const filePath = path.join(process.cwd(), 'public/uploads', filename);

  try {
    await writeFile(filePath, buffer);
    console.log('File saved to:', filePath);
    return { success: true, filename };
  } catch (error) {
    console.error('Error saving file:', error);
    return { error: 'Failed to save file.' };
  }
}

Validating File Uploads

It's crucial to validate uploaded files on the server-side to prevent security vulnerabilities and ensure data integrity. Always check:

  • File Type: Ensure the file's MIME type is among your allowed types (e.g., only images, not executable files).
  • File Size: Limit the maximum size to prevent denial-of-service attacks or excessive storage usage.

Client-side validation is helpful for user experience but can be bypassed, so server-side checks are mandatory.

Implementing Server-Side Validation

Here's how you can add basic type and size validation to your Server Action before saving the file. This makes your upload process much more robust and secure.

// app/actions.js (validation added)
'use server';
import { writeFile } from 'fs/promises';
import path from 'path';

const MAX_FILE_SIZE = 1024 * 1024 * 5; // 5MB
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'application/pdf'];

export async function validateAndSaveFile(formData) {
  const file = formData.get('myFile');
  if (!file || file.size === 0) return { error: 'No file.' };

  if (file.size > MAX_FILE_SIZE) {
    return { error: 'File too large (max 5MB).' };
  }
  if (!ALLOWED_TYPES.includes(file.type)) {
    return { error: 'Invalid file type.' };
  }

  const buffer = Buffer.from(await file.arrayBuffer());
  const filename = Date.now() + '-' + file.name;
  const filePath = path.join(process.cwd(), 'public/uploads', filename);

  await writeFile(filePath, buffer);
  return { success: true, filename };
}

Handling Multiple File Uploads

To allow users to upload multiple files at once, simply add the multiple attribute to your <input type="file"> tag.

On the server, formData.getAll('myFiles') will return an array of File objects, allowing you to iterate and process each one individually.

// HTML for multiple files:
<form action="/api/upload" method="POST" enctype="multipart/form-data">
  <input type="file" name="myFiles" multiple />
  <button type="submit">Upload</button>
</form>

// Server Action for multiple files:
'use server';

export async function uploadMultipleFiles(formData) {
  const files = formData.getAll('myFiles');
  if (!files || files.length === 0) return { error: 'No files.' };

  const uploadedNames = [];
  for (const file of files) {
    // Perform validation and saving for each file
    console.log('Processing file:', file.name);
    uploadedNames.push(file.name);
  }
  return { success: true, uploadedNames };
}

Beyond Local Storage

While saving files locally is suitable for development and small projects, production applications often use cloud storage solutions for scalability, reliability, and security.

Popular options include AWS S3, Google Cloud Storage, and Cloudinary. Server Actions can integrate directly with these services by sending the file's ArrayBuffer to their respective SDKs, providing robust storage capabilities.

File Upload Quiz

Which of the following HTML attributes is absolutely essential for a basic form to correctly send file data to a Next.js Server Action?

Recap & Next Steps

You've learned how to handle file uploads using Next.js Server Actions!

  • Set up HTML forms with enctype="multipart/form-data" and <input type="file">.
  • Access uploaded files as File objects from the FormData object in your Server Actions.
  • Save files to disk using Node.js fs/promises by converting the File object's content via Buffer.from(await file.arrayBuffer()).
  • Implement crucial server-side validation for file types and sizes to enhance security.
  • Handle multiple file uploads by adding the multiple attribute to the input and using formData.getAll().

Next, explore how to provide optimistic UI updates for a smoother user experience after an action!

자주 묻는 질문

“액션을 활용한 파일 업로드” 강의는 무료인가요?

네 — “액션을 활용한 파일 업로드” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Next.js 15 Fullstack (App Router + Server Actions) 강의 전체를 잠금 해제할 수 있습니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 3개의 강의가 포함되어 있습니다.

“액션을 활용한 파일 업로드”에서 뭘 배우나요?

안전한 저장과 처리를 포함하여 Server Actions를 통해 파일 업로드를 직접 처리하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 Next.js 15 Fullstack (App Router + Server Actions)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Next.js 15 Fullstack (App Router + Server Actions)을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Next.js 15 Fullstack (App Router + Server Actions)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 2번째 강의입니다.

“액션을 활용한 파일 업로드” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Next.js 15 Fullstack (App Router + Server Actions) 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Next.js 15 Fullstack (App Router + Server Actions) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 낙관적 UI 업데이트
  2. 액션을 활용한 파일 업로드
  3. Server Actions의 검증과 오류 처리
← Next.js 15 Fullstack (App Router + Server Actions)(으)로 돌아가기