I’m working on a Rails project that has Google OAuth implemented and can display files from Google Drive. I want to add a feature that lets users upload files from their computers to Google Drive by clicking an upload button.
The authentication part is working fine, and I can view the documents list. However, I’m having trouble with the file upload functionality. It should allow users to select a file and transfer it to their Google Drive account.
Could someone share a clear example of how to set up the file upload? I’m looking for useful code that includes the Rails controller logic and any required API calls to Google. I would appreciate guidance on the implementation process.
for sure! the google-api-client gem is super useful here. just call the drive service’s files.create method and include your file data as the media body. just a tip, don’t forget to specify the oauth scope as drive.file or you might run into permission issues.
Rails setup is key here. Make sure your form accepts file uploads with multipart/form-data, then grab the file in your controller with params[:file]. You’ll need to initialize the Google Drive service using the authenticated user’s credentials before hitting the API. I store the access token in the session - works great. For the Drive API call, use Google::Apis::DriveV3::MediaUpload.new(file.tempfile, content_type: file.content_type) to pass the file content. Don’t forget to handle rate limits since Google will throttle you during heavy usage.
I hit the same issues last year when building this. The trick is getting your controller to handle file uploads correctly. You’ll want to use a multipart upload request with the Google Drive API - just make sure you’re setting the right MIME type and handling the file stream properly. What tripped me up was getting the request headers right and making sure files don’t hit Google Drive’s size limits. For bigger files, add progress tracking since users hate waiting without feedback. The docs are pretty confusing, but stick with the files.create endpoint and set uploadType to multipart - it’s way simpler.