AI 이미지 생성 프로젝트 ( AI Seller ) - [4] / 프로그레스바 구현하기(SSE)
만약 50장의 사진을 업로드 시 사용자는 아무런 화면이 없으면 백엔드에서 얼마나 작업이 완료되었는지 알 방법이 없다.
프로그레스바 구현

뿌듯
만약 50장의 사진을 업로드 시 사용자는 아무런 화면이 없으면 백엔드에서 얼마나 작업이 완료되었는지 알 방법이 없다.
기존 모든 프로젝트에서는 요청 시간이 길어봤자 1초여서 이러한 생각을 못하였는데 사진의 갯수가 많고 이를 SD 모델이 처리하다 보니
시간이 생각보다 오래걸려 개발한 나 조차도 얼머나 걸리는지 몰라 새로고침하거나 개발자 도구를 켜는 상황을 볼 수 있었다.
하여 프로그래스바를 개발하기로 결정하였다.
저번 프로젝트에서 WebSocket 으로 실시간 채팅 및 활동 추적을 구현한 적이 있었다.
허나 이번 프로젝트에서는 백엔드에서 프론트로 해당 task 의 작업 완료도만 가져오면 된다.
따라서 SSE(Server-Sent Events) 를 구현해 보기로 하였다.
SSE 는 단방향 통신으로써 현재 프로그래스바를 구현하기에 매우 적합하다!!
특징부터 알고 가겠다.
SSE 와 WebSocket 의 차이점
| 특성 | SSE | WebSocket |
|---|---|---|
| 통신 방향 | 단방향 (서버 -> 클라이언트) | 양방향 (서버 <-> 클라이언트) |
| 프로토콜 | HTTP | WebSocket (독립적 프로토콜) |
| 연결 유지 | 자동 재연결 지원 | 애플리케이션 레벨 재연결 필요 |
| 데이터 형식 | 텍스트 (text/event-stream) | 텍스트 및 바이너리 |
| 일반 사용 사례 | 실시간 알림, 피드 업데이트 | 채팅, 게임, 스트리밍 |
코드 구현 과정
먼저 서버에 업데이트 함수 헤더를 설정해둔다.
try {
// SSE 헤더 설정
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
previewUrl: result.previewUrl
// 진행 상황 업데이트 함수
const updateProgress = (progress) => {
res.write(JSON.stringify({ progress }) + '\n');
};
진행 상황 업데이트 함수 구현한다.
async processImage(type, file, customBackground = null, progressCallback = null) {
console.log('=== processImage 시작 ===');
console.log('Type:', type);
throw new Error(`이미지 업로드 실패: ${errorText}`);
const serverUrl = this.getNextServer();
this.serverQueues.get(serverUrl).push(file);
console.error('ComfyUI 업로드 오류:', error);
try {
if (progressCallback) progressCallback(10);
const uploadResult = await this.uploadImage(file, serverUrl);
prompt: workflow,
if (progressCallback) progressCallback(30);
let backgroundUploadResult = null;
if (type === 'background' && customBackground) {
backgroundUploadResult = await this.uploadImage(customBackground, serverUrl);
}
prompt: workflow,
if (progressCallback) progressCallback(50);
const workflow = this.getWorkflow(type);
const modifiedWorkflow = this.modifyWorkflow(workflow, {
inputImage: uploadResult.name,
backgroundImage: backgroundUploadResult?.name
});
const formData = new FormData();
if (progressCallback) progressCallback(70);
const promptResult = await this.executeWorkflow(modifiedWorkflow, serverUrl);
const result = await response.json();
if (progressCallback) progressCallback(90);
const result = await this.waitForResult(promptResult.prompt_id, serverUrl);
const result = await response.json();
if (progressCallback) progressCallback(100);
return {
...result,
serverUrl
};
} finally {
- 이미지 업로드 시작 (10%)
- 업로드 완료 (30%)
- 워크플로우 준비 (50%)
- 이미지 처리 시작 (70%)
- 결과 대기 (90%)
- 처리 완료 (100%)
2. 프론트엔드 구현 (React)
상태 관리
const [isProcessing, setIsProcessing] = useState(false);
const [progress, setProgress] = useState(0);
진행 상황 수신 및 처리
const reader = response.body.getReader();
}
while (true) {
const { value, done } = await reader.read();
if (done) break;
if (result.success) {
const lines = value.split('\n');
for (const line of lines) {
if (!line.trim()) continue;
try {
const result = JSON.parse(line);
if (result.progress) {
setProgress(result.progress);
}
if (result.success && result.data?.url) {
setProcessedImage(result.data.url);
setDownloadUrl(result.data.url);
setOriginalFileName(studioImage.file.name);
incrementQuota('studio');
}
} catch (e) {
console.error('JSON 파싱 오류:', e);
}
}
}
UI 컴포넌트
{isProcessing && (
<div className="progress-bar-container">
<div
className="progress-bar"
style={{ width: `${progress}%` }}
/>
<span className="progress-text">{progress}%</span>
</div>
)}