@@ -83,17 +83,61 @@ STORAGES = {
8383}
8484```
8585
86- ## Example: Usage
86+ # Example 1: Saving directly to S3 via FileField
87+ # This will automatically use the given bucket configured in ImportExportS3.
8788
8889```
89- # it will save the image in given bucket.
9090class PublicImage(models.Model):
9191 file = models.FileField(storage=ImportExportS3())
92+ ```
93+
94+ # Example 2: Saving a file via model's save() method
95+ # Useful if you need to process or manipulate the file before uploading.
96+ ```
97+ class PublicImage(models.Model):
98+ file = models.FileField()
99+
100+ def save(self, *args, **kwargs):
101+ # Only upload if a file is provided
102+ if self.file and hasattr(self.file, 'file'):
103+ storage = ImportExportS3()
104+ # Save file content to S3
105+ saved_name = storage.save(self.file.name, self.file)
106+ # Update the file name to the S3 path
107+ self.file.name = saved_name
108+
109+ super().save(*args, **kwargs)
110+ ```
92111
112+ # Example 3: Uploading a file from a remote URL (binary download or streaming)
113+ # Useful for fetching external content and storing it directly in S3.
93114
94115```
116+ import requests
117+ from django.core.files.base import ContentFile
95118
119+ class PublicImage(models.Model):
120+ image = models.URLField(blank=True, null=True)
96121
122+ def save(self, *args, **kwargs):
123+ # Fetch an image from a remote URL
124+ image_url = "https://www.edx.org/contentful/ii9ehdcj88bc/2SkUwC7Kf9G5I5b49hjVgu/1fa2453e92e46d980f9f99cf08a51e73/image_processing.jpg?w=435&h=245&fm=webp"
125+ response = requests.get(image_url)
126+
127+ if response.status_code == 200:
128+ # Wrap content in Django ContentFile
129+ content = ContentFile(response.content)
130+
131+ # Use custom S3 storage to save
132+ storage = ImportExportS3()
133+ file_name = storage.save("deb.png", content)
134+
135+ # Update the model field with the S3 URL
136+ self.image = storage.url(file_name)
137+
138+ # Save model instance
139+ super().save(*args, **kwargs)
140+ ```
97141
98142> ** Note:**
99143> You can place these custom storage classes in any appropriate module (such as ` storages.py ` ), and reference them in your ` STORAGES ` Django setting.
0 commit comments