[Django]-Best way to send files to GCS with Django

1πŸ‘

βœ…

The error may be because of incorrect use of fileName and file. Try sync streaming of the file with upload request, like this :

from google.cloud import storage

def upload_file(file,projectName,bucketName, fileName, content_type):

    client = storage.Client(projectName)
    bucket = client.get_bucket(bucketName)
    blob = bucket.blob(fileName)

    blob.upload_from_string(
        file,
        content_type=content_type)

    url = blob.public_url
    if isinstance(url, six.binary_type):
        url = url.decode('utf-8')

    return url

For further reading, Reference.

3πŸ‘

This how I uploaded file via djano,
below shows the view method from my django(drf) view

def upload_gcp(self, request):
  file = request.data["file"]
  storage_client = storage.Client.from_service_account_json(
        'path-to-credentials-file.json'
    )
  bucket = storage_client.get_bucket("sandbox-bucket-001")
  blob = bucket.blob(file.name)
  blob.upload_from_string(file.file.read())

The file was sent as formdata and in this case, the uploaded file is contained in the key named file and the file python variable is the InMemoryUploadedFile object and file.name contains the actual name of the uploaded file

πŸ‘€lordvcs

0πŸ‘

#Looks like above methods are not working. I did something in this way

file_info= request.FILES['file']
bucket = storage_object.get_bucke`enter code here`t('bucket-name')
blob = bucket.blob('filename')
blob.upload_from_file(file_info.file, content_type='image/jpeg', 
rewind=True)
πŸ‘€sairahul099

Leave a comment