File size: 1,932 Bytes
999afa1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import os
from fastapi import FastAPI, File, UploadFile, HTTPException
from firebase_admin import credentials, initialize_app, storage
from uuid import uuid4
import json

# Khởi tạo FastAPI app
app = FastAPI()

# Đường dẫn đến file JSON chứa thông tin xác thực Firebase
firebase_creds = os.getenv("FIREBASE_CREDENTIALS")
cred_dict = json.loads(firebase_creds)
cred = credentials.Certificate(cred_dict)
initialize_app(cred, {
    'storageBucket': 'trans-paper.appspot.com'
})

# Cấu hình thư mục tạm thời để lưu file trước khi tải lên Firebase
UPLOAD_FOLDER = 'uploads'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

# Hàm để upload file lên Firebase
def upload_file_to_firebase(file_path: str, filename: str):
    bucket = storage.bucket()
    blob = bucket.blob(filename)
    blob.upload_from_filename(file_path)
    blob.make_public()  # Tạo đường dẫn công khai
    return blob.public_url

# API cho phép user tải ảnh lên
@app.post("/upload/")
async def upload_image(file: UploadFile = File(...)):
    try:
        file_name = f"{uuid4()}_{file.filename}"
        file_path = f"uploads/{file_name}"

        # Lưu file tạm vào thư mục
        with open(file_path, "wb") as buffer:
            buffer.write(await file.read())

        # Upload file lên Firebase
        public_url = upload_file_to_firebase(file_path, file_name)

        # Xóa file tạm sau khi upload
        if os.path.exists(file_path):
            os.remove(file_path)

        return {"message": "File uploaded successfully", "url": public_url}
    
    except Exception as e:
        # In ra thông báo lỗi chi tiết
        print(f"Error: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Upload failed: {str(e)}")

# Chạy ứng dụng với Uvicorn
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)