Hi all,
I have this custom API to upload the file to the S3 bucket. I need to override the existing file upload. By default, I need to use the S3 bucket for file uploads, below is my sample code
@frappe.whitelist()
def upload_file_to_s3():
uploaded_files = frappe.request.files.getlist("file")
if not uploaded_files:
frappe.throw("No files found in request")
s3_client = boto3.client(
"s3",
aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY,
region_name=S3_REGION
)
file_urls = []
for filedata in uploaded_files:
filename = secure_filename(filedata.filename)
file_content = filedata.stream.read()
unique_filename = f"{random_string(10)}-{filename}"
s3_key = f"frappe-uploads/{unique_filename}"
try:
# Upload file without ACL
s3_client.put_object(
Bucket=S3_BUCKET_NAME,
Key=s3_key,
Body=file_content,
ContentType=filedata.content_type
)
s3_url = f"https://{S3_BUCKET_NAME}.s3.{S3_REGION}.amazonaws.com/{s3_key}"
# Save file URL in Frappe
file_doc = frappe.get_doc({
"doctype": "File",
"file_name": filename,
"file_url": s3_url,
"is_private": 1
})
file_doc.insert(ignore_permissions=True)
frappe.db.commit()
file_urls.append(s3_url)
except Exception as e:
frappe.logger().error(f"Error uploading {filename} to S3: {str(e)}")
frappe.throw(f"Failed to upload {filename} to S3. {str(e)}")
return {"message": "Files uploaded successfully", "file_urls": file_urls}