在 Google Drive API 中将文件上传到特定文件夹

问题描述 投票:0回答:1

我正在尝试将文件上传到 Google Drive API 中的特定文件夹,但无法正常工作。我已经尝试通过 Apex 中的代码和使用 Postman 发出 HTTP 请求,但文件总是在根文件夹中结束。

这是我用来发出 HTTP 请求的 Apex 代码:

public void uploadFileToDrive(String folderId) {
   // Get the HTTP request body
   String requestBody = createRequestBody();
   String strEndpoint =  'https://www.googleapis.com/upload/drive/v3/files? 
   uploadType=multipart&parents=' + folderId;

    // Make the HTTP POST request to upload the file to the specified folder
    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint(strEndpoint);
    request.setHeader('Authorization', 'Bearer ' + access_token);
    request.setHeader('Content-Type', 'multipart/related; boundary="----boundary"');
    request.setBody(requestBody);
    request.setMethod('POST');
    HttpResponse response = http.send(request);
    if (response.getStatusCode() == 200) {
        // File uploaded successfully
        System.debug('File uploaded successfully to Google Drive');
    } else {
        // Error uploading file
        System.debug('Error uploading file to Google Drive: ' + response.getStatus() + ' - ' + response.getBody());
    }

}

我试过将文件夹 ID 传递给 URL 中的 parents 参数,如下所示:

https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&parents=%5C\

但它不起作用。该文件不断上传到根文件夹。

我也试过在 Postman 中测试端点,但我得到了相同的结果。这是我在表单数据中发送的内容:

Key: file, Value: test.png
Key: parents, Value: \<folder ID\>

我正在将 Content-Type 标头设置为 multipart/form-data。

谁能帮我弄清楚我做错了什么?提前谢谢你!

我正在尝试将文件上传到 Google Drive API 中的特定文件夹,但无法正常工作。我已经尝试通过 Apex 中的代码和使用 Postman 发出 HTTP 请求,但文件总是在根文件夹中结束。

我尝试将文件夹 ID 传递给 URL 中的 parents 参数,如下所示:

https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&parents=%5C\

我希望文件上传到指定的文件夹,但它一直上传到根文件夹。我也尝试在 Postman 中测试端点,但我得到了相同的结果。

谁能帮我弄清楚我做错了什么?提前谢谢你!

google-drive-api postman salesforce apex
1个回答
0
投票

文件夹 id 必须添加到表单数据中,而不是添加到 URL 中。但关键不是

parents
,而是
metadata
.

Key:metadata, value:{"parents":["folderid"]}

在此处查看元数据选项和正确的 JSON 表示:Google Drive API 文件概述.

您也可以查看我对您问题的评论,其中包含一些工作代码的链接。

© www.soinside.com 2019 - 2024. All rights reserved.