Uploading File from FileResoure to database

Hi,

In order to upload a file to a S3 bucket I need a file path. How can I get a file path from a file that I uploaded via a Viktor file upload field? Or are there other possibilities to do this?

KR.
Jan

Hi Jan,

To upload a file to S3, what do you need specifically?

  • weblink to a file
  • local path to a file
  • binary content of a file

I will assume you need a local path to the file. You can generate a temporary file to save the content to, and then pass that filename to the s3 uploader:

import os
from tempfile import NamedTemporaryFile


def upload_file_to_s3(params, **kwargs):
    # params.file_to_upload represents the file to be uploaded to s3
    tmp_file = NamedTemporaryFile(delete=False)
    # Write the binary content of the file to the temporary file
    tmp_file.write(params.file_to_upload.file.getvalue_binary())  
    tmp_file.close()
    # Now upload the file to s3
    s3_client.upload_file(file_name=tmp_file.name, ...)
    # Don't forget to remove the temporary file
    os.unlink(tmp_file.name)

Please let me know whether this solves your issue!

1 Like