John Amos
John Amos

Reputation: 75

Upload different files with identical filenames using boto3 and Django (and S3)

I am trying to create a Django server that stores media files on S3 where users can upload their own files that might all have the same filename but be different files. I have set up S3 and gotten it working via explicit python commands like

import boto3
s3 = boto3.resource('s3')
s3.Object('my-bucket','text.txt').put(Body=open('/text.txt', 'rb'))

I am setting up my model like this:

import boto3
s3 = boto3.resource('s3')
class MyModel(models.Model):
    my_file = models.FileField()
    file_url = models.CharField(max_length=200, blank=True, null=True)

In my views.py, my upload form is:

import boto3
s3 = boto3.resource('s3')

...

if form.is_valid():
    # creates object from form but doesn't go into database
    mymodel = form.save(commit=False)
    uploaded_file = request.FILES['my_file']
    s3.Object('my-bucket',uploaded_file.name).put(Body=request.FILES['uploaded_file'])
    mymodel.file_url = 'http://my-bucket.s3.amazonaws.com/' + uploaded_file.name;

I would like users to be upload their own files that might all have the same filename but be different files. I can imagine generating an md5 string and then appending that to the file name, but then when people go to download their files they will have a random hash string appended to the end of the file.

I assume there is a better, more elegant way to do this. Can anyone help?

Upvotes: 3

Views: 1307

Answers (1)

Preston Martin
Preston Martin

Reputation: 2963

If possible, I would have a unique identifier for the user, and upload all files for that user with the identifier appended to the url as a folder. An example would be if your bucket was mybucket, and your identifier was the userId, your upload url would be 'http://my-bucket.s3.amazonaws.com/' + user.Id + '/' + uploaded_file.name. S3 does not have a directory structure, but uses name prefixes as a way to make organize your files easier. Below is a link to the relevant documentation:

S3: Working with Folders

Upvotes: 1

Related Questions