0
votes

How to upload file to google drive using java. my java code is.

HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
    httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE))
    .setAccessType("online")
    .setApprovalPrompt("auto").build();

String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
System.out.println("Please open the following URL in your browser then type the authorization code:");
System.out.println("  " + url);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = br.readLine();

GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

//Create a new authorized API client
Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).build();

//Insert a file  
File body = new File();
body.setTitle("My document");
body.setDescription("A test document");
body.setMimeType("text/plain");

java.io.File fileContent = new java.io.File("document.txt");
FileContent mediaContent = new FileContent("text/plain", fileContent);

File file = service.files().insert(body, mediaContent).execute();
System.out.println("File ID: " + file.getId());
}}

So in that file object(java.io.File fileContent = new java.io.File("document.txt");) asking complete file path.But in file upload we can get only file name not path.How to resolve the problem.please help me.

1
I'm not quite sure what do you want to be in this issue. But if you want to get the file name instead of file path. The java.io.File.getName() method returns the last name of the pathname's name sequence, that means the name of the file. - Dayton Wang
Ok fine that if i pass file name in file-Content it was saying that filNotFoundException.That means it wants exact path where the file is located.But from web application you know we can get only file name.So how to resolve this issue. - kamesh
@kamesh, How are you getting file name in first place? - Sridhar
hi sridhar i am uploading file to Google drive through web application.so in this process we can get only file name from request object.so in this scenario it is asking absolute path.How can i provide file path.Is there any way to upload file to Google drive using web application with java...? - kamesh

1 Answers

-2
votes