I have a function to upload files to Google Drive.
I tried to upload with a pdf file, It's working.
public Task<String> createFilePDF(String filePath){
return Tasks.call(mExecutor,()->{
File fileMetaData = new File();
fileMetaData.setName("DinotesDemo");
java.io.File file = new java.io.File(filePath);
FileContent mediaContent = new FileContent("application/pdf",file);
File myFile = null;
try {
myFile = mDriveService.files().create(fileMetaData,mediaContent).execute();
}catch (Exception e){
}
if (myFile == null){
throw new IOException("Null result");
}
return myFile.getId();
});
}
And now, I need to upload the realm file to drive. What should I do?
Thanks very much!!
Related
I'm trying to execute a json file that shows 2 routes with bat files.
To read the file I'm using a path_provider to localize the json file, so that part I have it already done. I need to know why the program can't reconize the text. I put all the information inside a list bc is the correct way to read all the information.
dynamic complete_route = '';
_functionX(String args1, String args2) async {
var shell = Shell();
try {
final dir = await getApplicationDocumentsDirectory();
String d = dir.path;
final path = d;
final route = await ('$path\\config.json');
String contenido = await _leerArchivo(route);
String local_route = complete_route;
shell.run('$local_route $args1 $args2');
} catch (e) {
debug('error', true);
debug(e, true);
}
}
List lista = [];
_leerArchivo(String ruta) async {
try {
//final File f = File(ruta);
final res = await json.decode(ruta);
lista = res["routes"];
complete_route = res.toString();
return lista;
} catch (e) {
return e.toString();
}
}
Add permission in menifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Put below permission in <application .... /application>
android:requestLegacyExternalStorage="true"
rootBundle is used to access the resources of the application, it cannot be used to access the files in phone storage.
Open the file with
File jsonFile = await File("${dir.path}/demofolder/demo.json");
Then decode this jsonFile using
var jsonData = json.decode(jsonFile.readAsStringSync());
In my site, i gave download option to download the file. when i am checking in local server it is working properly. But after deploy the server, if i click the link means it will show the following error,
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.
My code here
public ActionResult Download(string fileName)
{
string pfn = Server.MapPath("~/Content/Files/" + fileName);
if (!System.IO.File.Exists(pfn))
{
//throw new ArgumentException("Invalid file name or file not exists!");
return Json(new JsonActionResult { Success = false, Message = "Invalid file name or file not exists!" });
}
else
{
return new BinaryContentResult()
{
FileName = fileName,
ContentType = "application/octet-stream",
Content = System.IO.File.ReadAllBytes(pfn)
};
}
}
This is my code. I don't know what mistake here, Can anyone find my problem and tell me ?
The Problem with ur code is that u r missing 'JsonRequestBehavior.AllowGet' while returning json.
public ActionResult Download(string fileName)
{
string pfn = Server.MapPath("~/Content/Files/" + fileName);
if (!System.IO.File.Exists(pfn))
{
//throw new ArgumentException("Invalid file name or file not exists!");
return Json(new JsonActionResult { Success = false, Message = "Invalid file name or file not exists!" },JsonRequestBehavior.AllowGet });
}
else
{
return new BinaryContentResult()
{
FileName = fileName,
ContentType = "application/octet-stream",
Content = System.IO.File.ReadAllBytes(pfn)
};
}
}
I created a document in google drive. I want to upload a new revision for the same document using google drive android sdk. I tried the code like,
try{
// First retrieve the file from the API.
File file = service.files().get(fileId).execute();
java.io.File fileContent = new java.io.File("sdcard0/temp/test.doc");
FileContent mediaContent = new FileContent("application/vnd.google-apps.document", fileContent);
File updatedFile = service.files().update(getID(), file, mediaContent).execute();
} catch (IOException e1) {
Log.d("","An error occurred: " + e1); //No i18n
} catch (Exception e){
Log.d("","EXCEPTION IN SAVING"+e); //No i18n
}
But the content looks like corrupted in docs.google.com like
Please guide me if am doing anything wrong.
Note: the same code works well for uploaded document.
You cannot use those revisions for native formats like google docs. Those have their own apis to modify them. For example spreadsheets has the spreadsheet feed api.
You can create a new revision for a Google Docs/Spreadsheet format using the convert parameter in the update request.
Following your code modified to enable conversion while uploading (not tested but confident it's correct)
try{
// First retrieve the file from the API.
File file = service.files().get(fileId).execute();
java.io.File fileContent = new java.io.File("sdcard0/temp/test.doc");
FileContent mediaContent = new FileContent("application/msword", fileContent); //Changed the mime type to original
File updatedFile = service.files().update(getID(), file, mediaContent)
.setConvert(true) //Convert the file while uploading
.execute();
} catch (IOException e1) {
Log.d("","An error occurred: " + e1); //No i18n
} catch (Exception e){
Log.d("","EXCEPTION IN SAVING"+e); //No i18n
}
I was just curious, is it possible to have direct network transfers in c#, without local caching.
e.g.
I have response stream which represents GoogleDrive file and request stream to upload file to another GoogleDrive account.
At that momment I can download file to local pc and next upload it to the google drive. But is it possible to upload it directly from one google drive to another or, at least, start uploading before full download will be completed.
Thank
Yes you can, with Google Drive api you download file into a stream and you keep it in memory so you can upload it to another google drive account after login.
You get your token on first account and download a file keeping it in a stream.
THen you authenticate on other google drive account and upload the file using the stream.
PS: When you are inserting the file on the second drive account, instead of getting
the byte[] array reading the file from disk you get the byte array from the stream you have in memory.
File Download Example:
public static System.IO.Stream DownloadFile(
IAuthenticator authenticator, File file) {
if (!String.IsNullOrEmpty(file.DownloadUrl)) {
try {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
new Uri(file.DownloadUrl));
authenticator.ApplyAuthenticationToRequest(request);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK) {
return response.GetResponseStream();
} else {
Console.WriteLine(
"An error occurred: " + response.StatusDescription);
return null;
}
} catch (Exception e) {
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
File insert example:
private static File insertFile(DriveService service, String title, String description, String parentId, String mimeType, String filename) {
// File's metadata.
File body = new File();
body.Title = title;
body.Description = description;
body.MimeType = mimeType;
// Set the parent folder.
if (!String.IsNullOrEmpty(parentId)) {
body.Parents = new List<ParentReference>()
{new ParentReference() {Id = parentId}};
}
// File's content.
byte[] byteArray = System.IO.File.ReadAllBytes(filename);
MemoryStream stream = new MemoryStream(byteArray);
try {
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType);
request.Upload();
File file = request.ResponseBody;
// Uncomment the following line to print the File ID.
// Console.WriteLine("File ID: " + file.Id);
return file;
} catch (Exception e) {
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
}
Is it possible to upload and convert an HTML file to PDF using Google Drive API without user interaction?
Yes, it is, with two requests. You can import the file as a Google Docs, then export it to PDF. Using the Drive API.
https://developers.google.com/drive/v2/reference/files/insert
https://developers.google.com/drive/v2/reference/files/get
worked for me (Drive docs only...)
ByteArrayContent mediaContent = new ByteArrayContent("text/html", "HTML PAGE HERE".getBytes());
File body = new File();
body.setTitle("test.html");
body.setMimeType("text/html");
Insert request = null;
try
{
request = service.files().insert(body, mediaContent);
request.setConvert(true);
File file = request.execute();
HttpResponse resp = service.getRequestFactory().buildGetRequest(new GenericUrl(file.getExportLinks().get("application/pdf"))).execute();
OutputStream out = new FileOutputStream(getExternalFilesDir(null).getAbsolutePath() + "/test.pdf");
byte[] buf = new byte[1024];
int len;
while ((len = resp.getContent().read(buf)) > 0)
{
out.write(buf, 0, len);
}
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}