필터 지우기
필터 지우기

Writing a file to Google Drive?

조회 수: 95 (최근 30일)
Cris LaPierre
Cris LaPierre 2018년 11월 13일
댓글: Brian Wong 2023년 10월 31일
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
Cameron Sahagian-Crandall
Cameron Sahagian-Crandall 2022년 1월 19일
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 2023년 10월 31일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Raymond Guan
Raymond Guan 2019년 5월 27일
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
Cris LaPierre
Cris LaPierre 2020년 8월 27일
편집: Cris LaPierre 2020년 8월 27일
It is possible. I just tested using a csv file with a header row, 80,000 rows and 23 columns.
Sebastian Lemieux
Sebastian Lemieux 2020년 12월 11일
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?

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Steven Remington
Steven Remington 2018년 11월 16일
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.

카테고리

Help CenterFile Exchange에서 Google에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by