I'm trying to upload a file using the Google Drive api on Android
https://github.com/googlesamples/google-services/tree/master/android/signin/app/src/main/java/com/google/samples/quickstart/signin
I signed up to SignInActivityWithDrive.java in the link above.
But there is no example of uploading a file, downloading a file
I want to know how to upload and download files
Thank you
You can find basic examples of uploading and downloading in the docs.
Uploading
You can send upload requests in any of the following ways:
Simple upload: uploadType=media. For quick transfer of a small file (5 MB or less). To perform a simple upload, refer to
Performing a Simple Upload.
Multipart upload: uploadType=multipart. For quick transfer of a small file (5 MB or less) and metadata describing the file, all in
a single request. To perform a multipart upload, refer to
Performing a Multipart Upload.
Resumable upload: uploadType=resumable. For more reliable transfer, especially important with large files. Resumable uploads
are a good choice for most applications, since they also work for
small files at the cost of one additional HTTP request per upload.
To perform a resumable upload, refer to Performing a Resumable
Upload.
The following example shows how to upload an image using the client libraries:
File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveService.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute();
System.out.println("File ID: " + file.getId());
Downloading
Depending on the type of download you'd like to perform — a file, a
Google Document, or a content link — you'll use one of the following
URLs:
Download a file — files.get with alt=media file resource
Download and export a Google Doc — files.export
Link a user to a file — webContentLink from the file resource
An example of a basic download is:
String fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().get(fileId)
.executeMediaAndDownloadTo(outputStream);
It is 2022 now, and how the Google Drive API works might have changed significantly. I needed to upload a number of large files from a remote server where I have terminal access. This is how I got it working for me:
Use the steps detailed in this link to create a Google Services API (on your local computer) and get the API credentials. An extra step was required before step 3, go to the 'OAuth consent screen' tab on the panel to the left and complete necessary steps required. You have to do this only once. For free google accounts, you'll have to select External as the API type (but you can always keep the api in testing mode to not allow others to use it). Also add the gmail address you wish to use as a test user in this panel. Continue the rest of the steps from the aforementioned link.
From Step 1 you should get a client_secret_XXXXX.json file. Copy it to your remote computer working directory using SCP. Rename the file to client_secrets.json.
pip install pydrive
Import and run the following inside the remote working directory.
from pydrive.auth import GoogleAuth
gauth = GoogleAuth()
gauth.CommandLineAuth()
It will provide you a link that you can use to log into your google account from your local computer. You will get a login key that you will have paste into your remote terminal.
Upload a list of filenames
from pydrive.drive import GoogleDrive
drive = GoogleDrive(gauth)
for filename in filename_list:
## Enter folder ID here.
## You can get the folder Id from your drive link e.g.,
## https://drive.google.com/drive/u/2/folders/1pzschX3uMbxU0lB5WZ6IlEEeAUE8MZ-t
gfile = drive.CreateFile({'parents': [{'id': '1pzschX3uMbxU0lB5WZ6IlEEeAUE8MZ-t'}]})
gfile.SetContentFile(filename)
gfile.Upload() # Upload the file.
Related
I'm developing android app that recording voice and upload to google drive.
The simple solution is to save recording file to the local cache directory and then upload that file to google drive using google drive api.
But I want to upload recording file to google drive directly not saving into local cache directory.
Like this
recorder = MediaRecorder()
.apply {
setAudioSource(MediaRecorder.AudioSource.MIC)
setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
setOutputFile('googleDrivePath')
prepare()
}
recorder?.start()
But I don't know how to get google drive path
According to the docs:
Set the output file name using setOutputFile(). You must specify a file descriptor that represents an actual file.
As I also can’t find a way to retrieve the file as a byte array on a MediaRecorder in the javadoc, or redirect it to an OutputStream, I think I can assume it is impossible to not write it to a file.
I'm making something like online journal app, that will download "journal file" from Google Drive (via shared link) once and will update that file if it changes. Please, can anyone point me to some guides how to do it. I already tried to pin file from drive, but I don't really understand what to do next..
Downloading Files from Google Drive:
To download a Google Drive file via link, try this (from this tutorial):
https://drive.google.com/uc?export=download&id=FILE_ID
Just replace the FILE_ID with the original fileID found in the Drive URL.
Additonal notes:
You can download files using the DRIVE REST API
To download files, you make an authorized HTTP GET request to the file's resource URL and include the query parameter alt=media. For example:
GET https://www.googleapis.com/drive/v3/files/0B9jNhSvVjoIVM3dKcGRKRmVIOVU?alt=media
Authorization: Bearer ya29.AHESVbXTUv5mHMo3RYfmS1YJonjzzdTOFZwvyOAUVhrs
Downloading the file requires the user to have at least read access. Additionally, your app must be authorized with a scope that allows reading of file content. For example, an app using the drive.readonly.metadata scope would not be authorized to download the file contents. Users with edit permission may restrict downloading by read-only users by setting the viewersCanCopyContent field to true.
Updating files in Google Drive
Make an HTTP Request to Google Drive using PATCH. The PATCH method requests that a set of changes described in the request entity be applied to the resource identified by the Request- URI. Things to take note of are:
Parameters
Authorization
Request Body
I am trying to download files from Google drive. I am using the JAVA API for on android since Google says it provides more control over Google Drive.
So far I can download files, but I cannot download Google doc files.
I assume this is because in order to download a Google doc file it needs to be converted to PDF/Word/HTML before I can download it and the same reason why the size is unknown/0.
So my question is how can convert a Google doc to a word document and download it?
See Google REST API
https://developers.google.com/drive/web/manage-downloads
The Drive API allows you to download files that are stored in Google Drive. Also, you can download Google Documents (Documents, Spreadsheets, Presentations, etc.) and export them to formats that your app can handle. Drive also supports providing users direct access to a file via a link.
I assume you are looking for URL to query for exporting Doc type
url:'https://www.googleapis.com/drive/v3/files/' + fileId + '/export?mimeType=application/vnd.openxmlformats-officedocument.wordprocessingml.document'
method: GET
Content-Type: 'application/json'
Authorization: 'Bearer <Your oauth token>'
Alter mimeType parameter your required value as per allowed mime types here.
Response body contains the exported document.
You can test parameters with following wget command. It will export document in result.doc
wget --header="Authorization: Bearer <your Oauth token>" --header="Content-Type: application/json" --method=GET 'https://www.googleapis.com/drive/v3/files/{FileID}/export?mimeType=application/vnd.openxmlformats-officedocument.wordprocessingml.document' -O result.doc
Mimetypes are used to specify which format you want to download the file in.
So the problem was there was a space in my MimeType... that was giving me the error.
But use the following link for converting to different formats. Scroll to where it says Downloading Google Documents
Link
Im working on an app (flex 4.12 sdk, using flashbuilder 4.5, creating an app for ios and android, testing on an android htc one primarily)... and am using the camera to capture a file... Im then saving that image to the application storage directory, and I want to open the image in the default web browser or trigger a native dialog (android users) to choose the web browser of their choice... how it opens isnt really important right now -- Im mainly trying to just 'access' it with the device and 'load' it outside my air app...
heres the code I have:
var fs2 : FileStream = new FileStream();
fs2.addEventListener(Event.CLOSE, fileCompleteHandler);
var targetFile : File = File.applicationStorageDirectory.resolvePath("test.jpg");
fs2.openAsync(targetFile, FileMode.WRITE);
fs2.writeBytes(myBMDByteArray,0,myBMDByteArray.length);
fs2.close();
and for the event listener that detects the close of the newly created file:
function fileCompleteHandler(e:Event):void {
trace('File saved.');
trace('exists? ' + targetFile.exists);
trace('the url: ' + targetFile.url);
trace('path: ' + targetFile.nativePath);
navigateToURL(new URLRequest(targetFile.url));
}
I get the following info back from this listener
File saved.
exists? true
the url: app-storage:/test.jpg
path: /data/data/air.com.xxxxx.apptesting.debug/com.xxxxx.apptesting.debug/Local Store/test.jpg
... and problem is that navigateToURL cant access the location where the file is stored (the protocol shows in browser as file:///data/data/air.com/xxx... )
how can I use navigateToURL to get access to this newly created file in the web browser or whatever native application the device associates with the file (its a .JPG file)? I also have had success in adding the newly created image to the camera roll but couldnt figure out how to then open that newly saved image in the native camera roll or whatever app the device chooses or presents to the user for the .jpg format.
I can show the user the image INSIDE my app by referencing the bitmap data fine, I just want to give the user access to the physical file that Im creating on their device.
I even have had success in posting (via urlLoader) the bitmap data as base64 encoding and then creating a file on the server side and loading that url but the encoding and trip to and from the server to give the user the image adds a lot of overhead and it takes a little too long and I'd like to avoid that elongated process.
Thanks for any help anyone can provide - let me know if I need to be more specific in any of this.
Solved the issue... I was able to store / write my file in the documentsDirectory using:
var targetFile : File = File.documentsDirectory.resolvePath('test.jpg');
and then
navigateToURL(new URLRequest(targetFile.url));
And this works fine now. Hopefully it helps someone else! Seems that the storage directory SHOULD work but up until now I've only written to and read files stored there... maybe to open the files one HAS to copy it to a 'safe' location in the filesystem (i.e. sd card?)... will move on to test in ios Now - hope all works well in that OS. Thanks all who chimed in on this.
My first hunch is that you need to specify the proper user-permissions in your application descriptor so you can use the openWith functionality with content from your application.
Remember that you need to specify this for IOS and Android specifically.
On your application.xml you need this permissions set inside android > manifestAdditions > manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
With this permissions you can save files to applicationStorageDirectory:
const FILE_LOADER:URLLoader = new URLLoader();
FILE_LOADER.addEventListener(Event.COMPLETE, onTempFileComplete);
FILE_LOADER.dataFormat = URLLoaderDataFormat.BINARY;
FILE_LOADER.load(new URLRequest(BASE_URL + filePath));
The applicationStorageDirectory can only be accessed by the application it belongs too when using Android or iOS. navigateToURL() hands over your request to the default browser, which cannot access said directory.
documentsDirectory is a public directory in Android, but not in iOS. So it cannot be used for both platforms. Unfortunately none of the pre-compiled file paths File has point to a public directory in iOS. You can find a table explaining all the pre-compiled paths here
I try to make a file server to let people download APK file.My server is using Play framework.
the problem is :I always download a "app" file without file extension by PC browser.while using android browser, I always download a "app.bin" file. Is there anything wrong with my code?
test link:test download
public static Result get_app() {
File tmp = new File("Ele.apk");
response().setHeader("Content-Disposition", "attachment; filename=Ele.apk");
response().setContentType("mime/type");
return ok(tmp);
}`
There's no such Content-Type as mime/type or mime/apk as you trying to use it in the sample...
By Wikipedia description APK's Content-Type is application/vnd.android.package-archive and probably this one you should set.
If problem remains try to google what is valid Content-Type for serving these keys.