我正在尝试使用 C# 将图像文件上传到照片库。
使用的范围: https ://www.googleapis.com/auth/photoslibrary https://www.googleapis.com/auth/photoslibrary.appendonly
我正在使用以下方法生成 uploadToken:
FileStream fS = new FileStream(fullPath, FileMode.Open, FileAccess.Read);
byte[] b = new byte[fS.Length];
fS.Read(b, 0, (int)fS.Length);
fS.Close();
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://photoslibrary.googleapis.com/v1/uploads");
httpWebRequest.ContentType = "application/octet-stream";
httpWebRequest.Headers.Add("Authorization:" + "Bearer " + auth_Token);
httpWebRequest.Headers.Add("X-Goog-Upload-File-Name:" + imageName);
httpWebRequest.Headers.Add("X-Goog-Upload-Protocol:" + "raw");
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(b);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
在这里,我成功获取了 uploadToken。在此之后,我继续创建 mediaItem,如下所示:
httpWebRequest = (HttpWebRequest)WebRequest.Create("https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Authorization:" + "Bearer " + auth_Token);
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string albumID = "someid";
string itemDesc = "somedesc";
string jsonString = "{\"albumId\": \"" + albumID + "\",\"newMediaItems\": [{ \"description\": \"" + itemDesc + "\", \"simpleMediaItem\": { \"uploadToken\": \"" + uploadToken + "\" }}]}";
streamWriter.Write(jsonString);
streamWriter.Flush();
streamWriter.Close();
}
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
现在作为回应,我得到:
status": { "code": 3, "message": "NOT_IMAGE: There was an error while trying to create this media item." }
我用谷歌搜索了很多,但找不到任何解决此问题的方法或任何使用 Google Photos Library API 的 mediaUpload 代码块。
请建议我在哪里做错了。
- 以错误的方式读取/写入文件字节?
- 使用 Json 字符串并以错误的方式编写?
请帮我。谢谢你。