Search code examples
c++google-drive-apipoco-libraries

Upload file to Google Drive folder is failing


I am developing a function "uploading file to Google Drive folder" using c++ / Poco library.

File is always getting uploaded to root folder only

I have added optional parameter parents as below

std::string strParents = "[ { "id": "" + std::string(locationId) + ""} ]"

The code that I am currently using is as below and it uploads to root folder only.

    Poco::URI uri("https://www.googleapis.com/upload/drive/v3/files");
    uri.addQueryParameter("uploadType", "resumable");
    uri.addQueryParameter("supportsAllDrives", "true");
    uri.addQueryParameter("name", targetFilePath.filename().string());
    uri.addQueryParameter("description", "file from sdk");
    uri.addQueryParameter("properties", metaData);
    std::string strParents = "[ { \"id\": \"" + std::string(locationId) + "\"} ]";
    uri.addQueryParameter("parents", strParents);
    Poco::Net::HTTPRequest* req = new Poco::Net::HTTPRequest(Poco::Net::HTTPRequest::HTTP_POST, uri.toString(), Poco::Net::HTTPMessage::HTTP_1_1);
    req->add("Authorization", std::string("Bearer ") + accessToken);
    req->add("Content-Type", "application/json; charset=UTF-8");
    req->add("X-Upload-Content-Type", "application/octet-stream"); 
    req->add("X-Upload-Content-Length", std::to_string(iFileSize));
    //req->add("parents", std::string("[{\"id\":\"") + locationId + std::string("\"}]"));
    req->add("parents", strParents); // added here also as a trial

Whatever the format I set for parents option, its uploading to root folder only.


Solution

  • I have found the issue. The issue is with Poco usage.

    Its for those developers who are struggling like me.

    "parents" should be added as an array object. Not as a single key-value object

    if I add as below

    fileDataObject.add("parents", "[ id ]");

    its taking as a single value. When I stringify the post body, parents value appeared as below

    parents : "[ *id* ]"
    

    but it should come as

    parents : [ *id* ]
    

    Then I have added it as an array object as below

    Poco::JSON::Object fileDataObject;
    Poco::JSON::Array parents;
    parents.add(parentId);
    fileDataObject.set("name", targetFilePath.filename().generic_wstring());
    fileDataObject.set("parents", parents);