使用Java程序将文件上载到Google云端硬盘的共享链接

时间:2016-08-06 18:51:55

标签: java google-drive-api

我希望将我的java应用程序中的文件上传到最终用户提供的共享google驱动器链接。最终用户允许对共享的Google云端硬盘文件夹进行“可以修改”权限。我没有看到Google云端硬盘中的任何API可以帮助我将文件上传到用户的共享Google云端硬盘链接。当从浏览器访问此共享链接时,它显示的网页显示通过共享链接映射的文件夹下的文件列表,它允许我在空白区域上拖放文件以进行上载。由于此链接是网页,我无法使用java应用程序,因此寻找类似的API。

2 个答案:

答案 0 :(得分:0)

Google Drive API已记录在https://developers.google.com/drive/v3/web/quickstart/java

通常,您会将文档上传到Google云端硬盘中自己的根文件夹(“我的云端硬盘”),然后将文档移动或添加到其他用户共享的目标文件夹中。

答案 1 :(得分:0)

根据此documentationsupportsAllDrives=true参数通知Google云端硬盘您的应用程序旨在处理共享驱动器上的文件。但同时也提到supportsAllDrives参数在2020年6月1日之前有效。在2020年6月1日之后,将假定所有应用程序都支持共享驱动器。因此,我尝试使用Google Drive V3 Java API,发现V3 API的execute类的Drive.Files.Create方法当前默认支持共享驱动器。随附示例代码段供您参考。此方法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;
}
相关问题