Unable to download file created by my app on Google Drive, But can get the metadata of that file

前端 未结 3 938
暗喜
暗喜 2021-01-13 15:56

I followed all the steps mentioned in google drive sdk. I created a sample application on my device(android, running jelly bean) and am able to upload a file on to drive. Wh

3条回答
  •  独厮守ぢ
    2021-01-13 16:42

    I have answered this question, and all related Drive on Android questions, over here:

    Android Open and Save files to/from Google Drive SDK

    In that answer, I posted code for a method that I used to download files from Google Drive (if the following code by itself isn't clear, have a look at the complete answer that I linked to.)

    private java.io.File downloadGFileToJFolder(Drive drive, String token, File gFile, java.io.File jFolder) throws IOException {
        if (gFile.getDownloadUrl() != null && gFile.getDownloadUrl().length() > 0 ) {
            if (jFolder == null) {
                jFolder = Environment.getExternalStorageDirectory();
                jFolder.mkdirs();
            }
            try {
    
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(gFile.getDownloadUrl());
                get.setHeader("Authorization", "Bearer " + token);
                HttpResponse response = client.execute(get);
    
                InputStream inputStream = response.getEntity().getContent();
                jFolder.mkdirs();
                java.io.File jFile = new java.io.File(jFolder.getAbsolutePath() + "/" + getGFileName(gFile)); // getGFileName() is my own method... it just grabs originalFilename if it exists or title if it doesn't.
                FileOutputStream fileStream = new FileOutputStream(jFile);
                byte buffer[] = new byte[1024];
                int length;
                while ((length=inputStream.read(buffer))>0) {
                    fileStream.write(buffer, 0, length);
                }
                fileStream.close();
                inputStream.close();
                return jFile;
            } catch (IOException e) {        
                // Handle IOExceptions here...
                return null;
            }
        } else {
            // Handle the case where the file on Google Drive has no length here.
            return null;
        }
    }
    

提交回复
热议问题