【问题标题】:File Upload to Shared Link of the Google Drive using Java program使用 Java 程序将文件上传到 Google Drive 的共享链接
【发布时间】:2016-08-06 18:51:54
【问题描述】:
我希望将文件从我的 java 应用程序上传到最终用户提供的共享谷歌驱动器链接。最终用户已允许对共享的 google 云端硬盘文件夹具有“可以编辑”权限。我在 Google 云端硬盘中没有看到任何 API,可以帮助我将文件上传到用户的共享 Google 云端硬盘链接。当从浏览器访问此共享链接时,它会显示显示通过共享链接映射的文件夹下的文件列表的网页,它允许我将文件拖放到空白区域以进行上传。由于此链接是网页,因此我无法从 java 应用程序中使用,因此正在寻找类似的 API。
【问题讨论】:
标签:
java
google-drive-api
【解决方案2】:
根据documentation,supportsAllDrives=true 参数通知 Google Drive,您的应用程序旨在处理共享驱动器上的文件。但也提到supportsAllDrives参数有效期至2020年6月1日。2020年6月1日之后,假设所有应用程序都支持共享驱动器。因此,我尝试使用 Google Drive V3 Java API,发现当前在 V3 API 的 Drive.Files.Create 类的 execute 方法中默认支持共享驱动器。附上示例代码 sn-p 供您参考。此方法uploadFile 使用可恢复上传将文件上传到 Google 驱动器文件夹并返回上传的 fileId。
public static String uploadFile(Drive drive, String folderId , boolean useDirectUpload) throws IOException {
/*
* drive: an instance of com.google.api.services.drive.Drive class
* folderId: The id of the folder where you want to upload the file, It can be
* located in 'My Drive' section or 'Shared with me' shared drive with proper
* permissions.
* useDirectUpload: Ensures whether using direct upload or Resume-able uploads.
* */
private static final String UPLOAD_FILE_PATH = "photos/big.JPG";
private static final java.io.File UPLOAD_FILE = new java.io.File(UPLOAD_FILE_PATH);
File fileMetadata = new File();
fileMetadata.setName(UPLOAD_FILE.getName());
fileMetadata.setParents(Collections.singletonList(folderId));
FileContent mediaContent = new FileContent("image/jpeg", UPLOAD_FILE);
try {
Drive.Files.Create create = drive.files().create(fileMetadata, mediaContent);
MediaHttpUploader uploader = create.getMediaHttpUploader();
//choose your chunk size and it will be automatically divided parts
uploader.setChunkSize(MediaHttpUploader.MINIMUM_CHUNK_SIZE);
//As per Google, this enables gzip in future (optional) // got from another post
uploader.setDisableGZipContent(false);
//true enables direct upload, false resume-able upload
uploader.setDirectUploadEnabled(useDirectUpload);
uploader.setProgressListener(new FileUploadProgressListener());
File file = create.execute();
System.out.println("File ID: " + file.getId());
return file.getId();
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}