转让使用Google驱动器API上传的文件的所有权 [英] Transfer ownership of file uploaded using Google drive API
问题描述
Google Drive API无法传输从API本身上传的文件的所有权。
根据API文档,需要使用PUT转让所有权。
当我使用它与所需的参数,它返回现有的权限。
不会与新所有者更新。
如果我使用POST&所需的参数抛出'远程服务器返回一个错误:(400)错误的请求。'
我能够更改没有通过上传的文件的所有权API。与我从API上传的文件一样。所有者不会改变。
它是一个错误还是我做错了什么?
-EDIT -
如果有人想要使用API&我可以通过gdocs创建文件。
-EDIT2 -
public bool UploadReportToGoogleDrive(Model model,byte [] ReportPDF_ByteArray,string ddlAddFilesFolder =root,bool doNotify = true)
{
bool isErrorOccured = false;
尝试
{
SingletonLogger.Instance.Info(UploadReportToGoogleDrive - start);
FileList fileList = new FileList();
Google.Apis.Drive.v2.Data.File uploadedFile = new Google.Apis.Drive.v2.Data.File();
权限writerPermission = new Permission();
string accessToken = GetAccessToken();
#region查找报告文件夹
字符串url =https://www.googleapis.com/drive/v2/files?在application / vnd.google-apps中,
+access_token =+ accessToken
+& q =+ HttpUtility.UrlEncode(title ='My Reports'and trashed = false and mimeType。文件夹')
;
//创建POST数据并将其转换为字节数组。
列表< string> _postData = new List< string>();
string postData = string.Join(,_postData.ToArray());
尝试
{
WebRequest请求= WebRequest.Create(url);
string responseString = GDriveHelper.GetResponse(request);
fileList = JsonConvert.DeserializeObject< FileList>(responseString);
SingletonLogger.Instance.Info(UploadReportToGoogleDrive - 文件夹搜索成功);
}
catch(Exception ex)
{
SingletonLogger.Instance.Error(UploadReportToGoogleDrive\\FIND REPORT FOLDER,ex);
isErrorOccured = true;
#endregion FIND REPORT FOLDER
$ b $ if(fileList.Items.Count == 0)
{
#region CREATE REPORT FOLDER
url =https://www.googleapis.com/drive/v2/files? +access_token =+ accessToken;
//创建POST数据并将其转换为字节数组。
_postData = new List< string>();
_postData.Add({);
_postData.Add(\title \:\+我的报告+\,);
_postData.Add(\description \:\已上传Google Drive API\,);
_postData.Add(\parents \:[{\id \:\+root+\}],);
_postData.Add(\mimeType \:\+application / vnd.google-apps.folder+\);
_postData.Add(});
postData = string.Join(,_postData.ToArray());
尝试
{
WebRequest请求= WebRequest.Create(url);
byte [] byteArray = Encoding.UTF8.GetBytes(postData);
//设置WebRequest的ContentType属性。
request.ContentType =application / json;
//设置WebRequest的ContentLength属性。
request.ContentLength = postData.Length; // byteArray.Length;
//将请求的Method属性设置为POST。
request.Method =POST;
//获取请求流。
Stream dataStream = request.GetRequestStream();
//将数据写入请求流。
dataStream.Write(byteArray,0,byteArray.Length);
//关闭Stream对象。
dataStream.Close();
string responseString = GDriveHelper.GetResponse(request);
Google.Apis.Drive.v2.Data.File ReportFolder = JsonConvert.DeserializeObject< Google.Apis.Drive.v2.Data.File>(responseString);
;
ddlAddFilesFolder = ReportFolder.Id;
SingletonLogger.Instance.Info(UploadReportToGoogleDrive - 文件夹创建成功);
}
catch(Exception ex)
{
SingletonLogger.Instance.Error(UploadReportToGoogleDrive\\CREATE REPORT FOLDER,ex);
isErrorOccured = true;
}
#endregion CREATE REPORT FOLDER
}
else
{
ddlAddFilesFolder = fileList.Items.FirstOrDefault()。Id;
$ b $ if(!isErrorOccured)
{
#region上传新文件 - 存档流程
//创建元数据以发送
_postData = new List< string>();
_postData.Add({);
_postData.Add(\title \:\+Report_+ model.id +\,);
_postData.Add(\description \:\+person of report - +(model.borrowerDetails.firstName ++ model.borrowerDetails.lastName)+\ ,);
_postData.Add(\parents \:[{\id \:\+ ddlAddFilesFolder +\}],);
_postData.Add(\extension \:\+pdf+\,);
_postData.Add(\appDataContents \:\+ true +\,);
_postData.Add(\mimeType \:\+ GDriveHelper.GetMimeType(Report.pdf)。ToString()+\);
_postData.Add(});
postData = string.Join(,_postData.ToArray());
byte [] MetaDataByteArray = Encoding.UTF8.GetBytes(postData);
////创建数据文件
// MemoryStream target = new MemoryStream();
//myFile.InputStream.Position = 0;
//myFile.InputStream.CopyTo(target);
// byte [] FileByteArray = target.ToArray();
字符串边界=foo_bar_baz;
url =https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart+& access_token =+ accessToken;
WebRequest请求= WebRequest.Create(url);
request.Method =POST;
request.ContentType =multipart / related; boundary = \+ boundry +\;
// Wrighting元数据
字符串headerJson = string.Format( - {0} \r\\\
Content-Type:{1} \r\\\
\ r \ n,
边界,
application / json; charset = UTF-8);
string headerFile = string.Format(\r\\\
- {0} \r\\\
Content-Type:{1} \r\\\
\r\\\
,
边界,
GDriveHelper.GetMimeType(Report.pdf)。ToString());
string footer =\r\\\
--+ boundry +--\r\\\
;
int headerLenght = headerJson.Length + headerFile.Length + footer.Length;
request.ContentLength = MetaDataByteArray.Length + ReportPDF_ByteArray.Length + headerLenght;
Stream dataStream = request.GetRequestStream();
dataStream.Write(Encoding.UTF8.GetBytes(headerJson),0,Encoding.UTF8.GetByteCount(headerJson)); //写MetaData ContentType
dataStream.Write(MetaDataByteArray,0,MetaDataByteArray.Length); //写入元数据
dataStream.Write(Encoding.UTF8.GetBytes(headerFile),0,Encoding.UTF8.GetByteCount(headerFile)); //写入File ContentType
dataStream.Write(ReportPDF_ByteArray,0,ReportPDF_ByteArray.Length); //写入文件
//添加请求的结尾。从换行开始
dataStream.Write(Encoding.UTF8.GetBytes(footer),0,Encoding.UTF8.GetByteCount(footer));
dataStream.Close();
尝试
{
WebResponse response = request.GetResponse();
//获取包含服务器返回的内容的流。
dataStream = response.GetResponseStream();
//使用StreamReader打开流以便访问。
StreamReader reader = new StreamReader(dataStream);
//读取内容。
string responseFromServer = reader.ReadToEnd();
//显示内容。
//Console.WriteLine(responseFromServer);
uploadedFile = JsonConvert.DeserializeObject< Google.Apis.Drive.v2.Data.File>(responseFromServer);
//清理流。
reader.Close();
dataStream.Close();
response.Close();
SingletonLogger.Instance.Info(UploadReportToGoogleDrive - 上传到文件夹成功);
}
catch(Exception ex)
{
SingletonLogger.Instance.Error(UploadReportToGoogleDrive\\CREATE REPORT FOLDER,ex);
isErrorOccured = true;
//返回异常上传文件:上传文件。 + ex.Message;
#endregion上传新文件 - 存档流程
}
if(!isErrorOccured)
{
#region MAKE ADMIN ACCOUNT OWNER上传的文件 - 评论
url =https://www.googleapis.com/drive/v2/files/+ uploadedFile.Id
+/ permissions /
+ uploadedFile。所有者[0] .PermissionId
+?access_token =+ accessToken
+& sendNotificationEmails =+(doNotify?true:false)
;
WebRequest请求= WebRequest.Create(url);
string role =owner,type =user,value =aniketpatil87@gmail.com;
//创建POST数据并将其转换为字节数组。
postData ={
+\role \:\+ role +\
+,\type\: \+ type +\
+,\value \:\+ value +\
+,\permissionId \:\+ uploadedFile.Owners [0] .PermissionId +\
+,\transferOwnership \:\+true+\
+};
byte [] byteArray = Encoding.UTF8.GetBytes(postData);
//设置WebRequest的ContentType属性。
request.ContentType =application / json;
//设置WebRequest的ContentLength属性。
request.ContentLength = postData.Length; // byteArray.Length;
//将请求的Method属性设置为POST。
request.Method =POST;
//获取请求流。
Stream dataStream = request.GetRequestStream();
//将数据写入请求流。
dataStream.Write(byteArray,0,byteArray.Length);
//关闭Stream对象。
dataStream.Close();
// TRY CATCH - 如果令牌无效
尝试
{
字符串responseString = GDriveHelper.GetResponse(request);
SingletonLogger.Instance.Info(UploadReportToGoogleDrive - 使管理员帐户拥有者成功);
}
catch(Exception ex)
{
SingletonLogger.Instance.Error(UploadReportToGoogleDrive\\MAKE管理帐户所有者上载文件,例如);
isErrorOccured = true;
}
#endregion如果(model.Officer!= default(int))
(
#region ALLOW)使得上载文件的所有者
成为MAKE ADMIN帐户的所有者OFFICER访问上传的文件
OldModels.MWUsers officer = usersBL.GetAll(model.Officer).FirstOrDefault();
url =https://www.googleapis.com/drive/v2/files/+ uploadedFile.Id
+/ permissions /
// + uploadedFile .Owners [0] .PermissionId
+?access_token =+ accessToken
+& sendNotificationEmails =+(doNotify?true:false)
;
request = WebRequest.Create(url);
role =writer;
type =user;
值= Officer.EMail;
//创建POST数据并将其转换为字节数组。
postData ={
+\role \:\+ role +\
+,\type\: \+ type +\
+,\value \:\+ value +\
// +,\ permissionId\:\+ uploadedFile.Owners [0] .PermissionId +\
// +,\transferOwnership \:\+true +\
+};
byteArray = Encoding.UTF8.GetBytes(postData);
//设置WebRequest的ContentType属性。
request.ContentType =application / json;
//设置WebRequest的ContentLength属性。
request.ContentLength = postData.Length; // byteArray.Length;
//将请求的Method属性设置为POST。
request.Method =POST;
//获取请求流。
dataStream = request.GetRequestStream();
//将数据写入请求流。
dataStream.Write(byteArray,0,byteArray.Length);
//关闭Stream对象。
dataStream.Close();
// TRY CATCH - 如果令牌无效
尝试
{
字符串responseString = GDriveHelper.GetResponse(request);
SingletonLogger.Instance.Info(UploadReportToGoogleDrive - make officer writer success);
catch(Exception ex)
{
SingletonLogger.Instance.Error(UploadReportToGoogleDrive\\\\\ OFFOWO OFFICER TO ACCESS UPLOADED FILE,ex);
isErrorOccured = true;
}
#endregion允许管理员访问上载文件
}
}
if(isErrorOccured)
{
SingletonLogger。 Instance.Info(UploadReportToGoogleDrive - 报告上传到gdrive失败);
}
else
{
//LogHelper.CreateLogEntry (UserContext.CurrentUser.UserID,Uploaded+ myFileList.Count +file(s)on Google Drive。, this.HttpContext.Request);
SingletonLogger.Instance.Info(UploadReportToGoogleDrive - 报告上传到gdrive成功);
catch(Exception ex)
{
SingletonLogger.Instance.Info(UploadReportToGoogleDrive - Outer exception,ex);
isErrorOccured = true;
}
return isErrorOccured;
}
它看起来像是在文章正文中指定 transferOwnership
,当它必须被指定为URL参数时。
The Google Drive API is not able to transfer ownership of a file which was uploaded from the API itself.
as per the API documentation, PUT needs to be used for transferring ownership. when I use it with the parameters required it returns existing permission back. doesn't update it with new owner.
if i use POST & the required parameters it throws 'The remote server returned an error: (400) Bad Request.'
I was able to change the ownership for the files that were NOT uploaded via API. the same which I use for the files which are uploaded from API. the owner doesn't change.
Is it a bug or I am doing something wrong?
-EDIT- if anyone wants details of file uploaded using API & file created via gdocs I can.
-EDIT2-
public bool UploadReportToGoogleDrive(Model model, byte[] ReportPDF_ByteArray, string ddlAddFilesFolder = "root", bool doNotify = true)
{
bool isErrorOccured = false;
try
{
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - start");
FileList fileList = new FileList();
Google.Apis.Drive.v2.Data.File uploadedFile = new Google.Apis.Drive.v2.Data.File();
Permission writerPermission = new Permission();
string accessToken = GetAccessToken();
#region FIND REPORT FOLDER
string url = "https://www.googleapis.com/drive/v2/files?"
+ "access_token=" + accessToken
+ "&q=" + HttpUtility.UrlEncode("title='My Reports' and trashed=false and mimeType in 'application/vnd.google-apps.folder'")
;
// Create POST data and convert it to a byte array.
List<string> _postData = new List<string>();
string postData = string.Join("", _postData.ToArray());
try
{
WebRequest request = WebRequest.Create(url);
string responseString = GDriveHelper.GetResponse(request);
fileList = JsonConvert.DeserializeObject<FileList>(responseString);
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - folder search success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\FIND REPORT FOLDER", ex);
isErrorOccured = true;
}
#endregion FIND REPORT FOLDER
if (fileList.Items.Count == 0)
{
#region CREATE REPORT FOLDER
url = "https://www.googleapis.com/drive/v2/files?" + "access_token=" + accessToken;
// Create POST data and convert it to a byte array.
_postData = new List<string>();
_postData.Add("{");
_postData.Add("\"title\": \"" + "My Reports" + "\",");
_postData.Add("\"description\": \"Uploaded with Google Drive API\",");
_postData.Add("\"parents\": [{\"id\":\"" + "root" + "\"}],");
_postData.Add("\"mimeType\": \"" + "application/vnd.google-apps.folder" + "\"");
_postData.Add("}");
postData = string.Join("", _postData.ToArray());
try
{
WebRequest request = WebRequest.Create(url);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = postData.Length;//byteArray.Length;
// Set the Method property of the request to POST.
request.Method = "POST";
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
string responseString = GDriveHelper.GetResponse(request);
Google.Apis.Drive.v2.Data.File ReportFolder = JsonConvert.DeserializeObject<Google.Apis.Drive.v2.Data.File>(responseString);
;
ddlAddFilesFolder = ReportFolder.Id;
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - folder creation success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\CREATE REPORT FOLDER", ex);
isErrorOccured = true;
}
#endregion CREATE REPORT FOLDER
}
else
{
ddlAddFilesFolder = fileList.Items.FirstOrDefault().Id;
}
if (!isErrorOccured)
{
#region UPLOAD NEW FILE - STACKOVER FLOW
//Createing the MetaData to send
_postData = new List<string>();
_postData.Add("{");
_postData.Add("\"title\": \"" + "Report_" + model.id + "\",");
_postData.Add("\"description\": \"" + " report of person - " + (model.borrowerDetails.firstName + " " + model.borrowerDetails.lastName) + "\",");
_postData.Add("\"parents\": [{\"id\":\"" + ddlAddFilesFolder + "\"}],");
_postData.Add("\"extension\": \"" + "pdf" + "\",");
_postData.Add("\"appDataContents\": \"" + true + "\",");
_postData.Add("\"mimeType\": \"" + GDriveHelper.GetMimeType("Report.pdf").ToString() + "\"");
_postData.Add("}");
postData = string.Join(" ", _postData.ToArray());
byte[] MetaDataByteArray = Encoding.UTF8.GetBytes(postData);
//// creating the Data For the file
//MemoryStream target = new MemoryStream();
//myFile.InputStream.Position = 0;
//myFile.InputStream.CopyTo(target);
//byte[] FileByteArray = target.ToArray();
string boundry = "foo_bar_baz";
url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart" + "&access_token=" + accessToken;
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "multipart/related; boundary=\"" + boundry + "\"";
// Wrighting Meta Data
string headerJson = string.Format("--{0}\r\nContent-Type: {1}\r\n\r\n",
boundry,
"application/json; charset=UTF-8");
string headerFile = string.Format("\r\n--{0}\r\nContent-Type: {1}\r\n\r\n",
boundry,
GDriveHelper.GetMimeType("Report.pdf").ToString());
string footer = "\r\n--" + boundry + "--\r\n";
int headerLenght = headerJson.Length + headerFile.Length + footer.Length;
request.ContentLength = MetaDataByteArray.Length + ReportPDF_ByteArray.Length + headerLenght;
Stream dataStream = request.GetRequestStream();
dataStream.Write(Encoding.UTF8.GetBytes(headerJson), 0, Encoding.UTF8.GetByteCount(headerJson)); // write the MetaData ContentType
dataStream.Write(MetaDataByteArray, 0, MetaDataByteArray.Length); // write the MetaData
dataStream.Write(Encoding.UTF8.GetBytes(headerFile), 0, Encoding.UTF8.GetByteCount(headerFile)); // write the File ContentType
dataStream.Write(ReportPDF_ByteArray, 0, ReportPDF_ByteArray.Length); // write the file
// Add the end of the request. Start with a newline
dataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
dataStream.Close();
try
{
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
//Console.WriteLine(responseFromServer);
uploadedFile = JsonConvert.DeserializeObject<Google.Apis.Drive.v2.Data.File>(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - upload to folder success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\CREATE REPORT FOLDER", ex);
isErrorOccured = true;
//return "Exception uploading file: uploading file." + ex.Message;
}
#endregion UPLOAD NEW FILE - STACKOVER FLOW
}
if (!isErrorOccured)
{
#region MAKE ADMIN ACCOUNT OWNER OF UPLOADED FILE - COMMENTED
url = "https://www.googleapis.com/drive/v2/files/" + uploadedFile.Id
+ "/permissions/"
+ uploadedFile.Owners[0].PermissionId
+ "?access_token=" + accessToken
+ "&sendNotificationEmails=" + (doNotify ? "true" : "false")
;
WebRequest request = WebRequest.Create(url);
string role = "owner", type = "user", value = "aniketpatil87@gmail.com";
// Create POST data and convert it to a byte array.
postData = "{"
+ "\"role\":\"" + role + "\""
+ ",\"type\": \"" + type + "\""
+ ",\"value\": \"" + value + "\""
+ ",\"permissionId\":\"" + uploadedFile.Owners[0].PermissionId + "\""
+ ",\"transferOwnership\": \"" + "true" + "\""
+ "}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = postData.Length;//byteArray.Length;
// Set the Method property of the request to POST.
request.Method = "POST";
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
//TRY CATCH - IF TOKEN IS INVALID
try
{
string responseString = GDriveHelper.GetResponse(request);
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - make admin account owner success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\MAKE ADMIN ACCOUNT OWNER OF UPLOADED FILE", ex);
isErrorOccured = true;
}
#endregion MAKE ADMIN ACCOUNT OWNER OF UPLOADED FILE
if (model.Officer != default(int))
{
#region ALLOW OFFICER TO ACCESS UPLOADED FILE
OldModels.MWUsers officer = usersBL.GetAll(model.Officer).FirstOrDefault();
url = "https://www.googleapis.com/drive/v2/files/" + uploadedFile.Id
+ "/permissions/"
//+ uploadedFile.Owners[0].PermissionId
+ "?access_token=" + accessToken
+ "&sendNotificationEmails=" + (doNotify ? "true" : "false")
;
request = WebRequest.Create(url);
role = "writer";
type = "user";
value = Officer.EMail;
// Create POST data and convert it to a byte array.
postData = "{"
+ "\"role\":\"" + role + "\""
+ ",\"type\": \"" + type + "\""
+ ",\"value\": \"" + value + "\""
//+ ",\"permissionId\":\"" + uploadedFile.Owners[0].PermissionId + "\""
//+ ",\"transferOwnership\": \"" + "true" + "\""
+ "}";
byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = postData.Length;//byteArray.Length;
// Set the Method property of the request to POST.
request.Method = "POST";
// Get the request stream.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
//TRY CATCH - IF TOKEN IS INVALID
try
{
string responseString = GDriveHelper.GetResponse(request);
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - make officer writer success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\ALLOW OFFICER TO ACCESS UPLOADED FILE", ex);
isErrorOccured = true;
}
#endregion ALLOW OFFICER TO ACCESS UPLOADED FILE
}
}
if (isErrorOccured)
{
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - report upload to gdrive failed");
}
else
{
//LogHelper.CreateLogEntry(UserContext.CurrentUser.UserID, "Uploaded " + myFileList.Count + " file(s) on Google Drive.", this.HttpContext.Request);
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - report upload to gdrive success");
}
}
catch (Exception ex)
{
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - Outer exception", ex);
isErrorOccured = true;
}
return isErrorOccured;
}
It looks like you are specifying transferOwnership
in the post body, when it must be specified as a URL parameter, as per the documentation.
这篇关于转让使用Google驱动器API上传的文件的所有权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!