user1222324562
user1222324562

Reputation: 1075

Google Drive API Upload File from String

Is it possible to upload a string to Google Drive instead of the file itself? In this example, the script assumes there is a physical file 'files/photo.jpg'. How can I upload a csv file or json file without it being physically located on my machine?

Here is what is in the above example

folder_id = '0BwwA4oUTeiV1TGRPeTVjaWRDY1E'
file_metadata = {
    'name': 'photo.jpg',
    'parents': [folder_id]
}
media = MediaFileUpload('files/photo.jpg',
                        mimetype='image/jpeg',
                        resumable=True)
file = drive_service.files().create(body=file_metadata,
                                    media_body=media,
                                    fields='id').execute()
print 'File ID: %s' % file.get('id')

But instead of a the file 'files/photo.jpg' I want to upload {'somekey' : 'somevalue'} as a json file instead.

Upvotes: 4

Views: 1647

Answers (3)

nikhiljpinto
nikhiljpinto

Reputation: 91

For those looking for a way of uploading a file which you receive from your frontend in your backend & want to upload it, here is an example.

The following case is, I am sending a text file from my frontend application using formdata & receiving it on the backend. Now this file, I want to upload to google drive.

The tech stack I'm using is Angular 8 for frontend & Tornado Python for backend.

Backend Python Code:

import io
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseUpload
from gdrive_config import credentials # Import your credentials object created using a service account 
# Refer this link for more info - https://github.com/googleapis/google-api-python-client/blob/master/docs/oauth-server.md

drive_service = build("drive", "v3", credentials=credentials, cache_discovery=False)

file = self.request.files
file_info = file["my_text_file"][0] # Here "my_text_file" is the key name you have set in form data

def upload_file(file_info):
    file_name = file_info["filename"]

    file_metadata = {
        "name": file_name,
        "mimeType": "text/plain", # Mimetype for text file
    }
    # If you print file_info, you will notice your text file data will be in the body & of type bytes.

    media = MediaIoBaseUpload(io.BytesIO(file_info["body"]), # **Pass your bytes object/string here.
                              mimetype="application/vnd.google-apps.document", # I'm converting text file to native google docs.
    # Keep the mimetype "text/plain", if you want to upload it as a text file itself.
                              resumable=True)

    file = drive_service.files().create(body=file_metadata,
                                        media_body=media,
                                        fields="id, name").execute()

    print("Uploaded File '{}' with ID: {}".format(file.get("name"), file.get("id")))

Reference links:

Oauth flow for service accounts - https://github.com/googleapis/google-api-python-client/blob/master/docs/oauth-server.md

Google drive python client docs - https://developers.google.com/resources/api-libraries/documentation/drive/v3/python/latest/drive_v3.files.html

Google drive upload file guide - https://developers.google.com/drive/api/v3/manage-uploads

Upvotes: 1

Tanaike
Tanaike

Reputation: 201378

  • You want to upload the string value as the CSV file or JSON file.
  • You want to achieve this using google-api-python-client with Python.

If my understanding is correct, how about this modification? Please think of this as just one of several answers.

Modified script:

When you use this, please set folder_id.

mimeType = 'text/csv'
text = 'a1, b1, c1\na2, b2, c2'
media = MediaIoBaseUpload(io.BytesIO(text.encode('utf-8')), mimetype=mimeType, resumable=True)

file_metadata = {'name': 'sampleName', 'parents': [folder_id], 'mimeType': mimeType}
file = drive_service.files().create(body=file_metadata,
                                    media_body=media,
                                    fields='id').execute()

Note:

  • This sample script supposes that you have already been able to upload files using Drive API.
  • If you want to upload text as JSON file. Please modify the mimeType and text.

References:

Upvotes: 4

GaryO
GaryO

Reputation: 6338

The simplest method is to write that JSON string out to a local file (perhaps in /tmp) and upload that.

Upvotes: 0

Related Questions