Writing a file to Google Drive?
Mostra commenti meno recenti
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
- Navigate to https://console.developers.google.com/
- Click on "Create Project" button. Then click "Create".
- Name it and click "Create".
- When the main screen reloads, click "Google Drive API"
- Click "Create Credentials"
- For credential type, select "Google Drive API", and "Other UI"
- Provide a client id and click "Create Oauth"
- From Dashboard, navigate to Credentials> OAuth Consent Screen
- click "Add Scope"
- Place a check next to Google Drive API - ../auth/drive.file and click "Add"
- Click Save.
Next, create an API token using the RunOnce function from Matlab to Google Sheets (matlab2sheets)
- Run the RunOnce function. The command window will display a url and a user code.
- Open the url address in a browser and, where prompted, paste the code.
- Sign into your google account and follow on screen prompts.
- When it asks to allow your App to access your google account, click "Allow".
- You can then close the browser.
- 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 Commenti
Cris LaPierre
il 13 Nov 2018
Modificato: Cris LaPierre
il 13 Nov 2018
Cris LaPierre
il 13 Nov 2018
Modificato: Cris LaPierre
il 13 Nov 2018
Raymond Guan
il 27 Mag 2019
Modificato: Raymond Guan
il 27 Mag 2019
I tried out your code but I'm running into a 403 error when I try to upload a file to my Google Drive. I have set up Oauth as instructed. For a sanity check, I also enabled the Sheets API and tried the matlab2sheets function, which ran perfectly. Is it still running on your end?
EDIT: Figured out my issue! Line 17 of RunOnce() must be modified from
scope_sheets = 'https://www.googleapis.com/auth/spreadsheets';
to
scope_sheets = 'https://www.googleapis.com/auth/drive.file';
kailash sahw shaw
il 27 Ago 2020
Dear Cris,
Their is error in line
headerFields = string(headerFields);
I could not able to execute it. As headerFields are cell and you are converting it to String. Kindly suggest.
Cris LaPierre
il 27 Ago 2020
kailash sahw shaw
il 29 Ago 2020
Thanks Cris, For pointing out the matlab version clue. I have updated my matlab to 2019a and it is working fine.
For my project, I have to do following
1. Create Folder in Gdrive 2. upload encrypted image to folder created 3. Access the folder for download, when required.
I could not able to load image as error message showing octate error.
Do you have any idea on it.
Cris LaPierre
il 29 Ago 2020
Cameron Sahagian-Crandall
il 19 Gen 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
il 31 Ott 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.
Risposta accettata
Più risposte (1)
Steven Remington
il 16 Nov 2018
0 voti
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.
Categorie
Scopri di più su Web Services in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!