unity3d Google Drive V3 API,创建文件夹并上传文件到其中

olhwl3o2  于 2023-03-30  发布在  Go
关注(0)|答案(3)|浏览(182)

我正在Unity中构建一个创建PDF文件的移动的应用程序。我希望该应用程序为要上传的文件创建一个文件夹。我发现下面的代码允许我上传文件并设置文件名,但这只是转到驱动器的根目录。我需要做些什么来创建一个名为“PDF文件”的文件夹,然后将新创建的文件添加到其中?

public async Task UploadToGoogleDriveAsync()
    {

        using (var client = new HttpClient())
        {
            Debug.Log(CloudData.instance.googleAccessToken);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",  CloudData.instance.googleAccessToken);
            //api endpoint
            var apiUri = new Uri("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart");

            // read the file content 
            var imageBinaryContent = new ByteArrayContent(LandlordCertLayout.instance.PDFDocumentBytes());
            imageBinaryContent.Headers.Add("Content-Type", "application/pdf");

            // prepare the metadata content
            string metaContent = "{\"name\":\"" + LandlordCertLayout.instance.PDFName + "\"}";
            byte[] byteArray = Encoding.UTF8.GetBytes(metaContent);
            var metaStream = new ByteArrayContent(byteArray);
            metaStream.Headers.Add("Content-Type", "application/json; charset=UTF-8");

            // create the multipartformdata content, set the headers, and add the above content
            var multipartContent = new MultipartFormDataContent("myboundry");
            multipartContent.Headers.Remove("Content-Type");
            multipartContent.Headers.TryAddWithoutValidation("Content-Type", "multipart/related; boundary=myboundry");
            multipartContent.Add(metaStream, "myboundry");
            multipartContent.Add(imageBinaryContent, "myboundry");

            HttpResponseMessage result = await client.PostAsync(apiUri, multipartContent);

            Debug.Log("Uploaded " + result);
        }
    }

我试过将内容类型更改为“application/vnd.google-apps.folder”,但总是出现错误400,而且我对HttpClient没有足够的了解。我已经搜索和搜索了好几天,但似乎什么都找不到。如果有任何提示,我将不胜感激。

xiozqbni

xiozqbni1#

您需要在为文件本身发送的元数据中包含父目录

var metaContent = "{\"name\":\"" + LandlordCertLayout.instance.PDFName + "\", \"parents\":\"[" + folderId + "]\"}";
bogh5gae

bogh5gae2#

感谢您的回复。我在创建文件夹时遇到了麻烦,因为我实际上没有一个文件夹来获取ID。但是,我现在已经成功地通过使用DriveService.Files.Create()从我保存的令牌创建Google UserCredential来完成此操作。
`string[] scopes = new string[] {”https://www.googleapis.com/auth/drive.file“};

var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
    {
        ClientSecrets = new ClientSecrets
        {
            ClientId = clientId,
            ClientSecret = clientSecret
        },
        Scopes = scopes,
        DataStore = new FileDataStore(Path.Combine(Application.persistentDataPath,".Credentials"), true)
    });

    var token = new TokenResponse { 
        AccessToken = googleAccessToken,
        RefreshToken = googleRefreshToken
    };

    UserCredential credential = new UserCredential(flow, Environment.UserName, token);`
thtygnil

thtygnil3#

文档看起来很清楚,首先创建一个文件夹,然后引用它的id:
若要在文件夹中创建文件,请使用files.create方法并在文件的parents属性中指定文件夹ID。下面的代码段显示如何使用客户端库在特定文件夹中创建文件:

// Upload file photo.jpg in specified folder on drive.
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
    Name = "photo.jpg",
    Parents = new List<string>
    {
        folderId
    }
};

https://developers.google.com/drive/api/guides/folder#create_a_file_in_a_folder

相关问题