'How do link a file user uploaded via pre-signed url to Database?
This is how I was saving user uploaded Files:
f = request.FILES[x]
s = File(file=f, user=curUser)
s.save()
This worked great but it took a lot of bandwidth on my server so I decided to use pre-signed urls.
Now users upload directly to s3 Bucket, however it's not linked to Database.
I tried this which runs after user successfully uploads to S3:
f = default_storage.open(userID + "/" + fileName)
curUser = User.objects.get(userID=userID)
s = File(file=f, user=curUser)
s.save()
f.close()
However, this is just creating a new folder on users directory and uploading it there.
my Models:
class User(models.Model):
userID = models.CharField(max_length=101,primary_key=True)
class File(models.Model):
user = models.ForeignKey(to=User, on_delete=models.CASCADE)
file = models.FileField(max_length=255, upload_to=user_directory_path)
def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
path = instance.user.userID + "/" + filename
return path
Solution 1:[1]
The most common method is to configure the s3 bucket to invoke a lambda function
on the file upload event.
Then inside your lambda you update the databse with the uploaded object.
Here is an example: https://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html
Solution 2:[2]
after doing this if your have done
makemigrationsand thenmigratethen table namedFilewill be created in your database.which will have two field user and file where file will contains the path of images uploaded.
now you can access the database like
File.objects.all()to get all the rows from File table.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gipsh |
| Solution 2 | chaitanya |
