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

前端 未结 3 923
暗喜
暗喜 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:33

    I don't think we need any Access Token to download a file. I had the same problem, and this worked:

    private class DownloadFile extends AsyncTask {
    
        private com.google.api.services.drive.model.File driveFile;
        private java.io.File file;
    
        public DownloadFile(File driveFile) {
            this.driveFile = driveFile;
        }
    
        @Override
        protected Boolean doInBackground(Void... params) {
            if (driveFile.getDownloadUrl() != null
                    && driveFile.getDownloadUrl().length() > 0) {
                try {
                    HttpResponse resp = mDriveService
                            .getRequestFactory()
                            .buildGetRequest(
                                    new GenericUrl(driveFile.getDownloadUrl()))
                            .execute();
                    OutputStream os = new FileOutputStream(file);
                    CopyStream(resp.getContent(), os);
                    os.close();
    
                    return true;
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            } else {
                return false;
            }
        }
    
        @Override
        protected void onPostExecute(Boolean result) {
            //use the file
        }
    }
    
    public static void CopyStream(InputStream is, OutputStream os) {
        final int buffer_size = 1024;
        try {
            byte[] bytes = new byte[buffer_size];
            for (;;) {
                int count = is.read(bytes, 0, buffer_size);
                if (count == -1)
                    break;
                os.write(bytes, 0, count);
            }
        } catch (Exception ex) {
        }
    }
    

提交回复
热议问题