Writing a file to Google Drive?

107 views (last 30 days)
Cris LaPierre
Cris LaPierre on 13 Nov 2018
Commented: Brian Wong on 31 Oct 2023
Motivated by the ability to use an api key to write a file to dropbox, as well as the ability to write to Google Sheets, I started looking into the ability to write a file to Google Drive. I have managed to write the file, but not set the filename. My digging would suggest MATLAB does not yet support anything other than a simple upload. Simple uploads do not include any metadata, which apparently includes name. You can read more in Google's documentation for uploading a file.
I have tried doing a simple upload and then setting the name property. I have also tried first naming a file and then adding data to it. Neither have worked.
I will caution that there was quite a bit of setup in Google needed first. For the ambitious, here are the steps:
First, enable Google Drive API
  1. Navigate to https://console.developers.google.com/
  2. Click on "Create Project" button. Then click "Create".
  3. Name it and click "Create".
  4. When the main screen reloads, click "Google Drive API"
  5. Click "Create Credentials"
  6. For credential type, select "Google Drive API", and "Other UI"
  7. Provide a client id and click "Create Oauth"
  8. From Dashboard, navigate to Credentials> OAuth Consent Screen
  9. click "Add Scope"
  10. Place a check next to Google Drive API - ../auth/drive.file and click "Add"
  11. Click Save.
Next, create an API token using the RunOnce function from Matlab to Google Sheets (matlab2sheets)
  1. Run the RunOnce function. The command window will display a url and a user code.
  2. Open the url address in a browser and, where prompted, paste the code.
  3. Sign into your google account and follow on screen prompts.
  4. When it asks to allow your App to access your google account, click "Allow".
  5. You can then close the browser.
  6. Return to the command window and press any key to finish execution.
I then modified the uploadToDropbox function from Upload files to your DropBox folder from MATLAB. For brevity, I've trimmed some code here.
function output = uploadToGoogle(dropboxAccessToken,varargin)
...
dataFile = varargin{1};
...
% Read file contents
try
fid = fopen(dataFile, 'r');
data = char(fread(fid)');
fclose(fid);
catch someException
throw(addCause(MException('uploadToGoogle:unableToReadFile','Unable to read input file.'),someException));
end
% Generate the custom header
[~,remoteFName, remoteExt] = fileparts(dataFile);
headerFields = {'Authorization', ['Bearer ', dropboxAccessToken]};
headerFields{2,1} = 'Content-Type';
headerFields{2,2} = 'application/octet-stream';
headerFields = string(headerFields);
% Set the options for WEBWRITE
opt = weboptions;
opt.MediaType = 'application/octet-stream';
opt.CharacterEncoding = 'ISO-8859-1';
opt.RequestMethod = 'post';
opt.HeaderFields = headerFields;
% Upload the file
try
tempOutput = webwrite('https://www.googleapis.com/upload/drive/v3/files?uploadType=media', data, opt);
catch someException
throw(addCause(MException('uploadToGoogle:unableToUploadFile','Unable to upload file.'),someException));
end
...
This allows me to upload an untitled file - no file extension or name. If I donwload that file as is but give it the original file extension, it appears to work.
The ask, then, is if anyone can help figure out how to get the file with a name and proper extension in Google Drive?
  9 Comments
Cameron Sahagian-Crandall
Cameron Sahagian-Crandall on 19 Jan 2022
I'm getting an error when running your code. I'm able to use mat2sheets without issue, and I tried changing line 17 of RunOnce.m to what was commented above. Here's the error:
Error using trytowritedatatogoogledrive
(line 27)
Unable to upload file.
Caused by:
Error using
matlab.internal.webservices.HTTPConnector/copyContentToByteArray
(line 396)
The server returned the status 401
with message "" in response to the
request to URL
https://www.googleapis.com/upload/drive/v3/files?uploadType=media.
Also, when I modified line 17 as was shown above, I got the following error. I'm super stuck, does anyone know where I might be going wrong?
Error using urlreadwrite (line 96)
Either the provided authentication method
is not supported or the username or
password provided are incorrect.
Error in urlread (line 47)
[s,status] =
urlreadwrite(mfilename,catchErrors,url,varargin{:});
Error in RunOnceDrive>getAccessToken (line
26)
deviceCodeString=urlread('https://accounts.google.com/o/oauth2/device/code','POST',
{'client_id', client_id, 'scope', scope});
Error in RunOnceDrive (line 18)
[aSheets,rSheets,tSheets] =
getAccessToken(client_id, client_secret,
scope_sheets);
Brian Wong
Brian Wong on 31 Oct 2023
I found out that your OAuth type for your Google API Credentials, needs to be "TV And Other Input Limited Devices", not Web Application. Then provide the script your client_id and client_secret and just follow the instructions.

Sign in to comment.

Accepted Answer

Raymond Guan
Raymond Guan on 27 May 2019
Not sure if you've figured this out already, but you can change the uploaded file name's name by slightly altering your posted code.
...
try
tempOutput = webwrite('https://www.googleapis.com/upload/drive/v3/files?uploadType=media', data, opt);
% update file name
mtdt = struct('name',[remoteFName remoteExt]);
headerFields{2,2} = 'application/json';
opt.HeaderFields = headerFields;
opt.RequestMethod = 'patch';
opt.MediaType = 'application/json';
webwrite(['https://www.googleapis.com/drive/v3/files/' tempOutput.id],mtdt, opt)
catch someException
...
  8 Comments
Cris LaPierre
Cris LaPierre on 27 Aug 2020
Edited: Cris LaPierre on 27 Aug 2020
It is possible. I just tested using a csv file with a header row, 80,000 rows and 23 columns.
Sebastian Lemieux
Sebastian Lemieux on 11 Dec 2020
I have utilized this tool, but am still getting an "Untilted" file in google drive. It would be nice to name the file, but my main goal is to extract the file ID so I can output a link to the file directly in a spreadsheet. Part of my Matlab scrpit outputs values to a google sheets using mat2sheets, and I would like one of the things output to be a direct link to the file I have uploaded to google drive.
Would anyone know how to exctract the file ID?

Sign in to comment.

More Answers (1)

Steven Remington
Steven Remington on 16 Nov 2018
One option that you could use java in order to interface more directly with their api like in this answers post:
Mostly because MATLAB is not natively support by Google's api so it may remove some complexity that way.

Products


Release

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!