Upload and Download from Firestore
Firestore, part of Firebase, is a powerful cloud-hosted NoSQL database that offers seamless file storage and retrieval through Firebase Storage. While integrating file upload and download data from Firestore in my Angular-18 frontend and Python backend project, Xor Geek encountered several challenges and found effective solutions. Here’s a breakdown of the issues and how Xor Geek resolved them.
1.For Upload File:
Challenge:
- The upload process needed to handle multiple files efficiently.
- Ensuring proper MIME types and encoding during upload to avoid corruption.
- Verifying file existence before attempting to upload to prevent overwriting.
Solution:
- Used Firebase Storage’s bucket system for storing files.
- Assigned correct MIME types while uploading files to avoid compatibility issues.
- Checked if the file existed before uploading, logging errors when necessary.
Here is Code:(Python)
file_names = [None] * 5
file_urls = [None] * 5 # To store the URLs of the uploaded files
attachments = []
if files:
bucket = storage.bucket() # Get the Firestore Storage bucket
for index, file in enumerate(files):
if index >= 5:
Break
if file and hasattr(file, 'filename'):
file_name = f"notificationMail/{timestamp}_{file.filename}"
blob = bucket.blob(file_name)
file.seek(0) # Reset file pointer before uploading
# Upload the file to Firestore Storage
blob.upload_from_string(file.read(), content_type=file.content_type)
2. File Download Issues and Fixes:
Challenge:
- Downloaded files were corrupted or had unsupported formats.
- Files downloaded but failed to open properly.
Solution:
- Ensured correct MIME types were set during upload in Python.
- Used response headers to handle different file formats properly.
- Implemented blob handling in Angular for correct file processing.
Here is Code:(Python)
def notification_download(self, filename):
Try:
bucket = storage.bucket()
blob = bucket.blob(f'notification/{filename}')
if not blob.exists():
return jsonify({"error": "File not found"}), 404
# Download the file locally
local_folder = "downloads"
os.makedirs(local_folder, exist_ok=True)
local_file_path = os.path.join(local_folder, filename)
blob.download_to_filename(local_file_path)
# Serve the file for download
return send_file(local_file_path, as_attachment=True, download_name=filename), 200
except Exception as e:
return {'error': str(e)}, 500
Conclusion
Integrating file upload and download data from Firestore with Angular-18 and Python backend came with its challenges, but leveraging Firebase’s tools and best practices helped overcome them. By implementing resumable uploads, metadata storage, security rules, and efficient download handling, Xor Geek ensured a seamless user experience while maintaining performance and security.
If you’re working with Firebase Storage and encountering similar issues, these strategies should help optimize your implementation and avoid common pitfalls!