如何在Android端通过编程方式修改Google Drive图片的访问权限为公开
Google Drive Android 上传文件设置公开访问权限方案
前置要求
- 你的应用必须已经申请了
https://www.googleapis.com/auth/drivescope,更低权限的scope(比如仅文件访问、只读权限)无法修改文件共享配置
实现步骤
文件上传成功后,你会得到对应文件的fileId,此时你只需要为该文件新增一条面向所有用户的只读权限即可,以下是两种常用实现方式:
方式1:使用Drive REST API(通用方案)
// 上传文件后获取返回的fileId String uploadedFileId = "上传成功后返回的文件ID"; // 构造权限请求参数 JSONObject permissionReq = new JSONObject(); try { // 权限角色设为只读 permissionReq.put("role", "reader"); // 授权对象设为所有人 permissionReq.put("type", "anyone"); } catch (JSONException e) { e.printStackTrace(); } // 发起权限设置请求 Request request = new Request.Builder() .url("https://www.googleapis.com/drive/v3/files/" + uploadedFileId + "/permissions") .addHeader("Authorization", "Bearer " + 你的应用当前持有的Google账号Access Token) .post(RequestBody.create(MediaType.parse("application/json"), permissionReq.toString())) .build(); new OkHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { // 处理权限设置失败逻辑 } @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { if (response.isSuccessful()) { // 权限设置成功,此时文件已支持公开访问 // 公开直链格式:https://drive.google.com/uc?id= + uploadedFileId } } });
方式2:使用Google Drive Android官方客户端库
如果你集成了官方的Drive SDK,可直接调用封装好的权限接口,无需自行构造HTTP请求:
Permission newPermission = new Permission(); newPermission.setRole("reader"); newPermission.setType("anyone"); drive.permissions().create(uploadedFileId, newPermission).execute();
注意事项
- 公开后的文件所有用户都可以无需登录访问,请勿上传涉及隐私的敏感内容
- 若需要取消公开权限,删除该条
type=anyone的权限配置即可
内容的提问来源于stack exchange,提问作者Bo Z
相关产品推荐
相关产品推荐

