4

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.

5
  • Can you provide your current script? Commented Jul 19, 2019 at 23:29
  • @Tanaike My current script is alike to what is in the above example Commented Jul 20, 2019 at 0:57
  • Thank you for replying and updating your question. I proposed a modified script as an answer. Could you please confirm it? If I misunderstood your question and that was not the result you want, I apologize. Commented Jul 20, 2019 at 1:18
  • Did my answer show you the result what you want? Would you please tell me about it? That is also useful for me to study. If this works, other people who have the same issue with you can also base your question as a question which can be solved. If you have issues for my answer yet, I apologize. At that time, can I ask you about your current situation? I would like to study to solve your issues. Commented Jul 23, 2019 at 22:35
  • Thank you for your response. Commented Jul 23, 2019 at 22:46

3 Answers 3

4
  • 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:

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.