从google drive

时间:2016-09-25 21:16:28

标签: c# asp.net google-api

我尝试允许用户从用户google驱动器中选择图片。 我按照这个文档:https://developers.google.com/picker/docs/。 当我从谷歌(' / drive / v2 / files /' + FileId)中重新获取图片网址时,我尝试在我的.NET代码中下载图片图片:

var WebRequest = (HttpWebRequest)System.Net.WebRequest.Create(url);
WebRequest.AllowWriteStreamBuffering = true;
WebRequest.Timeout = 30000;
WebRequest.KeepAlive = false;
WebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";
WebRequest.AllowAutoRedirect = true;
WebRequest.Headers.Add("Authorization", "Bearer " + token);                 

byte[] Arr;
using (var WebResponse = WebRequest.GetResponse())
{
     using (var Stream = WebResponse.GetResponseStream())
     {
          Arr = Stream.StreamToByteArray();
     }

     WebResponse.Close();
}
return Arr;

但我得到的只是一个空白(白色)网页。有了我从谷歌获得的网址,我可以在我的浏览器中显示图像,但我无法在我的代码中下载它。

如何下​​载图片?

1 个答案:

答案 0 :(得分:0)

改为使用WebClient

client = new WebClient();
client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
client.Headers.Add("Authorization", "Bearer " + token); 
client.AllowWriteStreamBuffering = true;
return client.DownloadData(url); /// DownloadData returns a byte array