从谷歌文档下载嵌入的图像

时间:2015-04-07 11:53:25

标签: google-api webclient webclient-download

我尝试使用其Drive API和WebClient在Google文档中下载嵌入图像。一些图像工作得很好,这是纯粹的图像。其他人通过重定向到登录页面而不是文件来响应,所以我想它与凭证有关(我现在没有为我的WebClient设置任何凭证)。失败的图像看起来像是图纸而不是图像。这可能是问题吗?

断开的链接如下所示: https://docs.google.com/a/irissystem.se/drawings/image?id=HERE_IS_AN_UNIQUE_ID&rev=1&h=81&w=28&ac=1

有没有办法使用DriveService类的HttpClient下载这样的图像,或者将我的凭据从我的DriveService应用到我的WebClient实例?

以下代码用于解析文档并下载图像。

foreach (HtmlNode img in doc.DocumentNode.SelectNodes("//img")) {
    HtmlAttribute src = img.Attributes["src"];
    using (WebClient webClient = new WebClient()) {
        byte[] data = webClient.DownloadData(src.Value);
        using (MemoryStream imagestream = new MemoryStream(data)) {
            byte[] imagebinary = imagestream.ToArray();
            Images.Add(src.Value, imagebinary);
        }
    }
}

更新

感谢下面的评论,我开始考虑HttpClient和下载流,结果证明这是一个很好的解决方案。下面的代码使用我的Google DataService(经过身份验证和完成)将嵌入文件作为流下载。这适用于绘图和图像,因此它是一个全面的解决方案。

public byte[] GetFileByUrl(string Url, string ExportType = "text/plain") {
    var stream = Service.HttpClient.GetStreamAsync(Url);
    var result = stream.Result;
    using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
        result.CopyTo(ms);
         return ms.ToArray();
    }
}

auth的代码如下所示

ServiceAccountCredential credential = new ServiceAccountCredential(
        new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL)
        {
            User = "xxx@xxx.com",
            Scopes = new[] { DriveService.Scope.Drive }
        }.FromCertificate(certificate));

Service = new DriveService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "xxx",
});

0 个答案:

没有答案
相关问题