'best way to send files to GCS with Django

what is the best way to send files to Google cloud storage with django.

this moment I'm getting the file with a post method

file = request.FILES['image']

but when I try to send to GCS

    from google.cloud import storage
    client = storage.Client(projectName)
    bucket = client.get_bucket(bucketName)
    blob = bucket.blob(fileName)
    blob.upload_from_filename(file)

I get this erros InMemoryUploadedFile so I have to save the file in a temp and after that send to GCS, but it is slow.



Solution 1:[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.

Solution 2:[2]

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 in 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

Solution 3:[3]

#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)

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 Prakhar Trivedi
Solution 2
Solution 3 sairahul099