patharanor commited on
Commit
3d87635
·
1 Parent(s): af43b14

feat: support upload image by multipart-form

Browse files
Files changed (1) hide show
  1. app.py +38 -2
app.py CHANGED
@@ -1,7 +1,8 @@
 
1
  import os, io, base64
2
  import uvicorn
3
  import logging
4
- from fastapi import FastAPI, Header
5
  from apis.s3 import S3
6
  from dotenv import load_dotenv
7
  from models.response import Response
@@ -91,10 +92,45 @@ async def upload(
91
  except Exception as e:
92
  res.error = str(e)
93
  logging.warning(f"Error during upload: {res.error}")
94
- return {"error": "Failed to upload content"}
95
 
96
  res.data = o.ref
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
 
98
  return res
99
 
100
  def is_valid(u, p):
 
1
+ from http import HTTPStatus
2
  import os, io, base64
3
  import uvicorn
4
  import logging
5
+ from fastapi import FastAPI, File, HTTPException, Header, UploadFile
6
  from apis.s3 import S3
7
  from dotenv import load_dotenv
8
  from models.response import Response
 
92
  except Exception as e:
93
  res.error = str(e)
94
  logging.warning(f"Error during upload: {res.error}")
 
95
 
96
  res.data = o.ref
97
+ return res
98
+
99
+
100
+ @app.post("/image2")
101
+ async def upload(
102
+ o: ImageObject,
103
+ x_request_user: str = Header(...),
104
+ x_api_key: str = Header(...),
105
+ file: UploadFile = File(...)
106
+ ):
107
+ res = Response()
108
+ logging.info("--------------------------------")
109
+ logging.info("Received request to upload image")
110
+
111
+ # Validate headers
112
+ if not is_valid(x_request_user, x_api_key):
113
+ res.status = HTTPStatus.FORBIDDEN
114
+ res.error = "Invalid credentials"
115
+ else:
116
+ key = f'{o.key}/{o.job_no}/{o.name}'
117
+ logging.info(f'Key for S3 upload: {key}')
118
+
119
+ try:
120
+ # Read the file content directly from UploadFile
121
+ file_content = await file.read()
122
+ logging.info(f'File content length: {len(file_content)} bytes')
123
+
124
+ # Upload file object to S3
125
+ # logging.info(f"Uploading file to S3 bucket '{AWS_S3_BUCKET_NAME}' with key '{key}'")
126
+ res = s3client.upload_file(AWS_S3_BUCKET_NAME, file_content, key)
127
+ logging.info("File uploaded successfully")
128
+
129
+ except Exception as e:
130
+ res.error = str(e)
131
+ logging.warning(f"Error during upload: {res.error}")
132
 
133
+ res.data = o.ref
134
  return res
135
 
136
  def is_valid(u, p):