Reputation: 249
I can upload files to my Google Drive account but I need to get the URL (link) of the file to use it later? example: https://docs.google.com/file/d/oB-xxxxxxxxxxx/edit
This is my method to upload file to Google Drive:
private void saveFileToDrive()
{
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
// Create URI from real path
String path;
path = "/sdcard/DCIM/Camera/a.png";
mFileUri = Uri.fromFile(new java.io.File(path));
ContentResolver cR = UploadActivity.this.getContentResolver();
// File's binary content
java.io.File fileContent = new java.io.File(mFileUri.getPath());
FileContent mediaContent = new FileContent(cR.getType(mFileUri), fileContent);
showToast("Selected " + mFileUri.getPath() + "to upload");
// File's meta data.
File body = new File();
body.setTitle(fileContent.getName());
body.setMimeType(cR.getType(mFileUri));
com.google.api.services.drive.Drive.Files f1 = mService.files();
com.google.api.services.drive.Drive.Files.Insert i1 = f1.insert(body, mediaContent);
File file = i1.execute();
if (file != null)
{
showToast("Uploaded: " + file.getTitle());
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
showToast("Transfer ERROR: " + e.toString());
}
}
});
t.start();
}
Upvotes: 0
Views: 1410
Reputation: 249
I got it, we just need to get the file ID and adding some string as in the following:
private void saveFileToDrive()
{
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
String ImageLink = null;
// Create URI from real path
String path;
path = "/sdcard/DCIM/Camera/b.mov";
mFileUri = Uri.fromFile(new java.io.File(path));
ContentResolver cR = UploadActivity.this.getContentResolver();
// File's binary content
java.io.File fileContent = new java.io.File(mFileUri.getPath());
FileContent mediaContent = new FileContent(cR.getType(mFileUri), fileContent);
showToast("Selected " + mFileUri.getPath() + " to upload");
// File's meta data.
File body = new File();
body.setTitle(fileContent.getName());
body.setMimeType(cR.getType(mFileUri));
com.google.api.services.drive.Drive.Files f1 = mService.files();
com.google.api.services.drive.Drive.Files.Insert i1 = f1.insert(body, mediaContent);
File file = i1.execute();
if (file != null)
{
showToast("Uploaded: " + file.getTitle());
}
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0)
{
ImageLink = "https://drive.google.com/open?id=" + file.getId() +"&authuser=0";
System.out.println("ImageLink: " + ImageLink);
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
showToast("Transfer ERROR: " + e.toString());
}
}
});
t.start();
}
Upvotes: 1