private async Task UploadWithAccessToken(string accessToken, string folderPath, string fileName, byte[] jpegData) { var parentId = await _driveHelper.GetFolderId(accessToken, folderPath); var metadata = new GoogleFileMetadata { Title = fileName, Parents = new GoogleFileParent[] { new GoogleFileParent { Id = parentId } } }; var byteArray = GetMultiPartUpload(metadata, jpegData); // Get the response var request = WebRequest.Create(_uploadFileAddress); request.ContentType = string.Format("multipart/related; boundary={0}", _multipartBoundary); request.ContentLength = byteArray.Length; request.Headers[HttpRequestHeader.Authorization] = string.Format("Bearer {0}", accessToken); request.Method = "POST"; using (var writeStream = await request.GetRequestStreamAsync()) { writeStream.Write(byteArray, 0, byteArray.Length); } var response = await request.GetResponseAsync(); string responseContent = null; using (var stream = response.GetResponseStream()) { using (var reader = new StreamReader(stream)) { responseContent = await reader.ReadToEndAsync(); } } }
private byte[] GetMultiPartUpload(GoogleFileMetadata metadata, byte[] jpegData) { var formData = string.Format(_multipartTemplate, JsonConvert.SerializeObject(metadata)); var formBytes = Encoding.UTF8.GetBytes(formData); var endBytes = Encoding.UTF8.GetBytes(_multipartTemplateEnd); var allBytes = new byte[formBytes.Length + jpegData.Length + endBytes.Length]; formBytes.CopyTo(allBytes, 0); jpegData.CopyTo(allBytes, formBytes.Length); endBytes.CopyTo(allBytes, formBytes.Length + jpegData.Length); return allBytes; }
private async Task<string> CreateFolder(string accessToken, string folderName, string parentId = null) { var metadata = new GoogleFileMetadata { Title = folderName, MimeType = "application/vnd.google-apps.folder" }; if (!string.IsNullOrEmpty(parentId)) { metadata.Parents = new GoogleFileParent[] { new GoogleFileParent { Id = parentId } }; } var byteArray = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(metadata)); // Get the response var request = WebRequest.Create(_createFolderAddress); request.ContentType = "application/json"; request.ContentLength = byteArray.Length; request.Headers[HttpRequestHeader.Authorization] = string.Format("Bearer {0}", accessToken); request.Method = "POST"; using (var writeStream = await request.GetRequestStreamAsync()) { writeStream.Write(byteArray, 0, byteArray.Length); } var response = await request.GetResponseAsync(); string responseContent = null; using (var stream = response.GetResponseStream()) { using (var reader = new StreamReader(stream)) { responseContent = await reader.ReadToEndAsync(); } } var parent = JsonConvert.DeserializeObject<GoogleFileParent>(responseContent); return parent.Id; }