목표
- Flutter 앱에서 이미지를 업로드하면, Flask 서버가 파일을 받아 임시 저장
- 추후 Gemini API 분석 단계에서 이 파일을 활용
라이브러리 준비
Flask와 함께 파일 업로드 처리를 위해 werkzeug가 필요합니다.
(Flask에 기본 포함되어 있어 추가 설치는 필요 없음)
코드 작성
app.py를 다음과 같이 수정합니다.
import os
from flask import Flask, request, jsonify
from werkzeug.utils import secure_filename
# Flask 앱 초기화
app = Flask(__name__)
# 업로드 폴더 지정
UPLOAD_FOLDER = "uploads"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# 허용 파일 확장자
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# 홈 라우트
@app.route('/')
def home():
return jsonify({"message": "IdeaSnap Backend is running!"})
# 이미지 업로드 API
@app.route('/api/upload-image', methods=['POST'])
def upload_image():
if 'image' not in request.files:
return jsonify({"error": "No file part"}), 400
file = request.files['image']
if file.filename == '':
return jsonify({"error": "No selected file"}), 400
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
return jsonify({
"message": "Image uploaded successfully",
"file_path": filepath
}), 200
return jsonify({"error": "Invalid file type"}), 400
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
프로젝트 구조 (지금까지)
ideasnap-backend/ ├─ uploads/ # 업로드된 파일이 저장될 폴더 ├─ app.py ├─ sample.jpg # 테스트할 이미지 파일 └─ venv/
터미널에서 프로젝트 폴더로 이동
cd ideasnap-backend
테스트 방법
터미널에서 curl을 사용해 업로드를 테스트할 수 있습니다.
curl -X POST http://127.0.0.1:5000/api/upload-image \ -F "image=@sample.jpg"
예상 응답
{
"message": "Image uploaded successfully",
"file_path": "uploads/sample.jpg"
}
Part 4에서는 업로드된 이미지를 Gemini API에 전달하여
👉 사진을 분석하고 키워드/아이디어(주제) 추출하는 기능을 구현합니다.
댓글 남기기