首页 > 解决方案 > 如何在 Xamarin 表单中将图像文件上传到 GoogleDrive

问题描述

我想知道是否有任何方法可以以 Xamarin 形式将图像从应用程序上传到 Google Drive,我使用此链接关注 Google Drive API

https://developers.google.com/drive/api/v3/manage-uploads

但在 xamarin 这种方式不起作用某些库不可用

这是我的代码

 var image = new Image

            {
                Source = ImageSource.FromFile(filepath)
            };

            var fileMetadata = new Google.Apis.Drive.v3.Data.File()
            {
                Name = "photo.jpg"
            };
            FilesResource.CreateMediaUpload request;
            using (var stream = new System.IO.FileStream(filepath,
                                    System.IO.FileMode.Open))
            {
                request = DriveService.Files.Create(
                    fileMetadata, stream, "image/jpeg");
                request.Fields = "id";
                request.Upload();
            }
            var file = request.ResponseBody;
            Console.WriteLine("File ID: " + file.Id);

DriveService 显示编译错误,我不知道这种方式是否可行,有什么帮助吗?

标签: c#xamarin.formsgoogle-api-dotnet-client

解决方案


Google Drive API 在 Xamarin.iOS 和 Xamarin.Android 中可用。因此您可以DependencyService在 iOS 和 Android 平台上使用和上传图像。

在表单中,创建界面

public interface IUploadFile
{
  void UploadFile(string filePath,string fileName);
}

iOS 实现

[assembly: Dependency(typeof(UploadFileImplementation))]
namespace xxx.iOS
{

  public class UploadFileImplementation : IUploadFile
  {
    public UploadFileImplementation () { }

    public UploadFile(string filePath,string fileName)
    {
        // upload file here

    }
  }
}

安卓实现

[assembly: Dependency(typeof(UploadFileImplementation))]
namespace xxx.Droid
{

  public class UploadFileImplementation : IUploadFile
  {
    public UploadFileImplementation () { }

    public UploadFile(string filePath,string fileName)
    {
        // upload file here

    }
  }
}

您可以从 nuget下载适用于iOSAndroid的Google Drive API。它提供了如何在本机平台上上传文件的示例。


推荐阅读