Drive Api Phone - java

I'm trying to create a java program that will create and upload excel files into a google drive. After uploading I need it to give permissions. I have done all thatbut the problem lies in trying to convert the excel files into a google files in order that people who use the sheets are able to update them with their phones. I have not been able to find any help on how to do this on the google api. Any help will be appreciated.

Assuming you have the path to your Excel file:
java.io.File fileContent = new java.io.File(excelfilepath);
FileContent mediaContent = new FileContent("application/vnd.ms-excel", fileContent);
// File's metadata.
File body = new File();
body.setTitle(fileContent.getName());
body.setMimeType("application/vnd.ms-excel");
// THIS IS THE IMPORTANT PART
Insert request = service.files().insert(body, mediaContent);
request.setConvert(true);
File file = request.execute();
// END OF THE IMPORTANT PART
if (file != null) {
showToast("Data Uploaded: " + file.getTitle());
}

Related

Google Drive API not downloading FIles (Java v3)

I'm using the code from here:
https://developers.google.com/drive/api/v3/manage-downloads#downloading_a_file
The code snippet I'm using is the following and placed in the main method:
String fileId = "some file ID";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().get(fileId)
.executeMediaAndDownloadTo(outputStream);
I have found no sign of the code actually downloading the file, nor do I know where the file is IF it actually downloads.
I'm not sure if I am using the proper scope to gain permission to download files. I am able to upload, list, and delete files as long as I know the fileID, but downloading seems to not work.
private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE);
Alternatively, I'm trying to create a method to enact the download protocol like so:
private static void downloadFile(Drive service, File file (or String fileID)){
}
but am not sure on how to do so. I've tried looking for samples online but most are from v1 or v2 apis and don't seem to work for me.
Also, I've read somewhere that it is not possible to download a Folder. Instead, I have to download each item in the folder one by one.
So do I have to make an Arraylist/list/array of the fileIDs and iterate through it after initializing a variable to represent fileID?
Edit: Some progress has been made, but I still have some problems I'm trying to thrash out.
List<File> files = result.getFiles();
File newFile;
if (files == null || files.isEmpty()) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
System.out.printf("%s (%s)\n", file.getName(), file.getId());
String fileId = file.getId();
//System.out.println(fileId);
String fileName = file.getName();
//System.out.println(fileName);
OutputStream outputstream = new FileOutputStream();
service.files().get(fileId)
.executeMediaAndDownloadTo(outputstream);
outputstream.flush();
outputstream.close();
}
What I want:
The above code is in the main method. I don't know if this is the proper way to do it, but as the program fetches each file and executes the System.out.printf, I also want it to download that file (with the same mimeType, and pref the same name too) into the destination set in the OutputStream constructor (C://User//some name//Downloads).
What I've tried:
From what I've tested, it only downloads the first file exactly the way I want, but only because I specify the name and extension in OutputStream. I've initialized variables 'fileId' and 'fileName' so that they will change according to the info as the program fetches the metadata for the next file, but I don't know how to change or set multiple constructors into this code:
OutputStream outputstream = new FileOutputStream();
service.files().get(fileId)
.executeMediaAndDownloadTo(outputstream);
to download all the files.
My folder hierarchy in Google Drive is like this:
Logs
-- bin (folder)
---- bunch of .bin files
-- .xml file
-- .xml file
You are using a ByteArrayOutputStream object as the output of your download. If your program terminates without having saved the contents of this object somewhere, you will not be able to find this information in your computer's disk, as it is not written to it but rather saved in memory as a buffered byte-array (refer to the previous link for more information).
If you want to save the output of the download to the file, I suggest you use instead a FileOutputStream as the destination of your download. In order to do that, you have to modify your code as follows:
Add the appropriate import declaration:
import java.io.FileOutputStream;
Modify your outputStream variable assignment as follows:
OutputStream outputStream = new FileOutputStream('/tmp/downloadedfile');
Where the parameter passed to FileOutputStream should be the desired destination path of your download.
After writing any contents to your file, add the following lines of code:
outputStream.flush();
outputStream.close();
This will ensure that your file is being written to properly.
In regards to downloading a folder, you are completely right - you will first need to fetch the folder you want to download, and each of their children. In order to better understand how to do it, I suggest you check out the following answer: Download folder with Google Drive API
Edit - example downloading a folder
String destinationFolder = "/tmp/downloadedfiles/";
List<File> files = result.getFiles();
File newFile;
if (files == null || files.isEmpty()) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
System.out.printf("%s (%s)\n", file.getName(), file.getId());
String fileId = file.getId();
String fileName = file.getName();
OutputStream outputstream = new FileOutputStream(destinationFolder + fileName);
service.files().get(fileId)
.executeMediaAndDownloadTo(outputstream);
outputstream.flush();
outputstream.close();
}
}

Spring web application save file to server

I build a web application.
I would like to read files from server, then generate PDF file ( with itText) then save it to the server.
I don't know how to locate the files from the server then save the file to the server.
I read from my PC and write data to my PC perfectly.
The above code works properly but just on my computer not at server.
String jspPath = "C:\\Users\\dave\\Desktop\\eclipse\\project\\";
String fileName = "CV.txt";
InputStreamReader ir = new InputStreamReader(new FileInputStream(jspPath+filename), "UTF-8");
// Then generate the PDF with iText
//and
FileOutputStream fs = new FileOutputStream(jspPath+"generated.pdf");
PdfWriter pdfWriter = new PdfWriter(fs);
PdfDocument pdfdoc = new PdfDocument(pdfWriter);
JSP path references to my folder not the link with the generated pdf.
I would like :
put CV.txt to the server and read it.
Generate pdf ( it will work).
Save the generated PDF to server
A link to the generated PDF which i can download.
Thanks in Advance
Here are few things which might help you.
You can use FormData to pass text file from Frontend to Backend.
Use ajax post call to pass data.
you will have entire file on backend in the RequestContext parameter as FileItem object. you can start reading file using InputStreamReader.
than convert it into pdf file.
you can save pdf file to java temporary directory
String temporaryDir = System.getProperty("java.io.tmpdir");
this will return path for java temporary directory and you can delete this pdf file later
you will have to create ResponseBuilder with content-type='application/pdf' to download as a pdf file and return it to the UI. read this post
Hope this information helps you to solve your issue!

oreilly multipartrequest class to upload multiple images

i am using oreilly multipartrequest class to upload multiple images, images are getting uploaded fine , but i want to know the name of all the images uploaded per request.
i am trying to print all filename using the below but it is printing the name of the last file only. I am trying to upload files 1.jpg , 2.jpg , 3.jpg , but it is printing only 3.jpg , what should i modify in the code to make it print all names.:
MultipartRequest m = new MultipartRequest(request, "C:/Users/;
Enumeration files = m.getFileNames();
while (files.hasMoreElements()) {
String name = (String) files.nextElement();
filename = m.getFilesystemName(name);
System.out.println(filename);
}
You can also list the files by making a file with the directory you wish to list.
File dir = new File(directory);
for (File f : dir.listFiles()){
System.out.print(f.getName());
}
Hope this helps
For more refernce check this link:
Oracle reference on File class

Save file in specific folder with Google Drive SDK

I've been trying to save a plain text file into a specific folder in Google Drive on Android.
So far using the Documentation and QuickStart Guide on Google Drive I have been able to do a few things that are going in the right direction, first I was able to create a plain text file:
File body = new File();
body.setTitle(fileContent.getName());
body.setMimeType("text/plain");
File file = service.files().insert(body, textContent).execute();
I have been able to create a new folder in the base directory of Google Drive with:
File body = new File();
body.setTitle("Air Note");
body.setMimeType("application/vnd.google-apps.folder");
File file = service.files().insert(body).execute();
I have also been able to list all of the folders in the user's Google Drive account with:
List<File> files = service.files().list().setQ("mimeType = 'application/vnd.google-apps.folder'").execute().getItems();
for (File f : files) {
System.out.println(f.getTitle() + ", " + f.getMimeType());
}
However I am a bit stuck on how to save a text file into a folder within Google Drive.
You need to use the parent parameter to put a file in a folder using insert. More details at https://developers.google.com/drive/v2/reference/files/insert
Something like this
File body = new File();
body.setTitle(fileContent.getName());
body.setMimeType("text/plain");
body.setParents(Arrays.asList(new File.ParentReference().setId(parentId));
File file = service.files().insert(body, textContent).execute();
If you want to INSERT a file in specific folder in Google Drive then follow these steps. Lets assume that we have retrieved all folder from the Drive and now i will INSERT an empty file in the first folder from the list, So
//Getting Folders from the DRIVE
List<File> files = mService.files().list().setQ("mimeType = 'application/vnd.google-apps.folder'").execute().getItems();
File f =files.get(1)//getting first file from the folder list
body.setTitle("MyEmptyFile");
body.setMimeType("image/jpeg");
body.setParents(Arrays.asList(new ParentReference().setId(f.getId())));
com.google.api.services.drive.model.File file = mService.files().insert(body).execute();
Now this will create an empty file in the Folder which are at the top in the retrieve file list.
Step1 : Create a folder
File body1 = new File();
body1.setTitle("cloudbox");
body1.setMimeType("application/vnd.google-apps.folder");
File file1 = service.files().insert(body1).execute();
Step2 : Insert your file
File body2 = new File();
body2.setTitle(fileContent.getName());
body2.setMimeType("text/plain");
body2.setParents(Arrays.asList(new ParentReference().setId(file1.getId())));
File file2 = service.files().insert(body2, mediaContent).execute();

Get a file given a path to the file

I want to get a file which i saved in a specific directory on my phone.
How can I find and get a ref to it so I can do with it something different like uploading to a server?
Thanks in advance.
Shiran
Well where do you store your file?
Store the file in a specific area such as
Environment.getExternalStorageDirectory()
Then when you want to read it, just use the file name used and the path obtained from the above method.
File f = new File("location");
Remember, if you're trying to access the sd card you need to set permissions. Then just handle the "file" in whatever way it is you're trying to do something.
If you're looking to use the SDCard check this post:
Permission to write to the SD card
[Edit - Example]
String filenameToWrite = "Test.jpg"
try{
File f = new File(Environment.getExternalStorageDirectory() + "/Photos/");
if (f.exists()){
File fileToWrite = new File(Environment.getExternalStorageDirectory() + "/Photos/" + filenameToWrite;
// Do something to write file, save bitmap, save byte stream, etc.
}
} catch(IOException e){
Log.e("File", "Could not save file, error occured: " + e.toString());
}
Here's a few getting started tutorials to help you understand how to read and write files in java. This (apart from the 'path') is a java question, not an Android one.
Tutorials:
http://beginwithjava.blogspot.com/2011/04/java-file-save-and-file-load-objects.html
http://www.roseindia.net/java/beginners/java-write-to-file.shtml

Categories