public void Upload(Stream fileStream) { var body = new Google.Apis.Drive.v2.Data.File(); body.Title = "My document 123"; body.Description = "A test document"; body.MimeType = "text/plain"; FilesResource.InsertMediaUpload request = GoogleDriveService.Files.Insert(body, fileStream, "text/plain"); request.Upload(); Google.Apis.Drive.v2.Data.File file = request.ResponseBody; Console.WriteLine("File id: " + file.Id); Console.WriteLine("Press Enter to end this process."); Console.ReadLine(); }
public GoogleDriveStream(GoogleDriveStorage storage, Google.Apis.Drive.v2.Data.File file) { this.storage = storage; this.file = file; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(file.DownloadUrl)); request.Headers.Add("Authorization", storage.Credential.Token.TokenType + " " + storage.Credential.Token.AccessToken); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode != HttpStatusCode.OK) throw new Exception("Could not retrieve file stream"); using (Stream responseStream = response.GetResponseStream()) responseStream.CopyTo(dataStream); dataStream.Seek(0, SeekOrigin.Begin); }
private async Task<string> CreateDirectory(string title, string parent = null) { File directory = null; File body = new File { Title = title, MimeType = "application/vnd.google-apps.folder" }; try { FilesResource.InsertRequest request = this.service.Files.Insert(body); directory = await request.ExecuteAsync(); } catch (Exception e) { throw new Exception(e.Message); } return directory.Id; }
public async Task<string> UploadImageToCloud(byte[] byteArrayContent, string fileName, string fileExstension, string parentPath = WebStorageConstants.Collection) { // var parentId = await this.CreateDirectory(parentPath); File body = new File { Title = fileName, // Parents = new List<ParentReference>() { new ParentReference() { Id = parentId } } }; MemoryStream stream = new MemoryStream(byteArrayContent); try { FilesResource.InsertMediaUpload request = this.service.Files.Insert(body, stream, "image/" + fileExstension); var result = await request.UploadAsync(); return WebStorageConstants.GoogleDriveSourceLink + request.ResponseBody.Id; } catch (Exception e) { throw new Exception(e.Message); } }
protected static string GetParentDriveId(DriveFile driveEntry) { return driveEntry == null || driveEntry.Parents == null || driveEntry.Parents.Count == 0 ? null : driveEntry.Parents[0].Id; }
/// <summary> /// Create a new file and return it. /// </summary> public static Google.Apis.Drive.v2.Data.File InsertResource(Google.Apis.Drive.v2.DriveService service, IAuthenticator auth, String title, String description, String mimeType, String content) { // File's metadata. Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File(); body.Title = title; body.Description = description; body.MimeType = mimeType; byte[] byteArray = Encoding.ASCII.GetBytes(content); MemoryStream stream = new MemoryStream(byteArray); Google.Apis.Drive.v2.FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType); request.Upload(); return request.ResponseBody; }
private static bool IsDriveFolder(DriveFile driveFolder) { return driveFolder != null && driveFolder.MimeType == GoogleDriveStorage.GoogleFolderMimeType; }
/// <summary> /// Uploads File into Google Drive. /// </summary> /// <param name="fileBytes">byte[] of the file</param> /// <param name="fileNameWithExtension">File-name with extension or path ending with the filename with extension. For example: picture.jpg </param> /// <returns>File ID in Google Drive. On error returns null.</returns> public string UploadFile(byte[] fileBytes, string fileNameWithExtension) { CheckToken(ref this.credential); var body = new Google.Apis.Drive.v2.Data.File(); body.Title = fileNameWithExtension; body.Description = "File uploaded by JustMeet"; body.MimeType = GetMimeType(fileNameWithExtension); ////body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } }; string result = null; using (var stream = new MemoryStream(fileBytes)) { try { FilesResource.InsertMediaUpload request = this.instance.Files.Insert(body, stream, body.MimeType); ////request.Convert = true; // uncomment this line if you want files to be converted to Drive format request.Upload(); result = request.ResponseBody.Id; } catch (Exception) { result = null; } } return result; }
protected Folder ToFolder(DriveFile driveEntry) { if (driveEntry == null) return null; if (driveEntry is ErrorDriveEntry) { //Return error entry return ToErrorFolder(driveEntry as ErrorDriveEntry); } if (driveEntry.MimeType != GoogleDriveStorage.GoogleFolderMimeType) { return null; } var isRoot = IsRoot(driveEntry); var folder = new Folder { ID = MakeId(driveEntry), ParentFolderID = isRoot ? null : MakeId(GetParentDriveId(driveEntry)), CreateBy = GoogleDriveProviderInfo.Owner, CreateOn = isRoot ? GoogleDriveProviderInfo.CreateOn : (driveEntry.CreatedDate.HasValue ? driveEntry.CreatedDate.Value : default(DateTime)), FolderType = FolderType.DEFAULT, ModifiedBy = GoogleDriveProviderInfo.Owner, ModifiedOn = isRoot ? GoogleDriveProviderInfo.CreateOn : (driveEntry.ModifiedDate.HasValue ? driveEntry.ModifiedDate.Value : default(DateTime)), ProviderId = GoogleDriveProviderInfo.ID, ProviderKey = GoogleDriveProviderInfo.ProviderKey, RootFolderCreator = GoogleDriveProviderInfo.Owner, RootFolderId = MakeId(), RootFolderType = GoogleDriveProviderInfo.RootFolderType, Shareable = false, Title = MakeFolderTitle(driveEntry), TotalFiles = 0, /*driveEntry.Count - childFoldersCount NOTE: Removed due to performance isssues*/ TotalSubFolders = 0, /*childFoldersCount NOTE: Removed due to performance isssues*/ }; if (folder.CreateOn != DateTime.MinValue && folder.CreateOn.Kind == DateTimeKind.Utc) folder.CreateOn = TenantUtil.DateTimeFromUtc(folder.CreateOn); if (folder.ModifiedOn != DateTime.MinValue && folder.ModifiedOn.Kind == DateTimeKind.Utc) folder.ModifiedOn = TenantUtil.DateTimeFromUtc(folder.ModifiedOn); return folder; }
protected static bool IsRoot(DriveFile driveFolder) { return IsDriveFolder(driveFolder) && GetParentDriveId(driveFolder) == null; }
protected String MakeFileTitle(DriveFile driveFile) { var ext = string.Empty; if (driveFile == null || string.IsNullOrEmpty(driveFile.Title)) { return GoogleDriveProviderInfo.ProviderKey; } Tuple<string, string> mimeData; if (GoogleDriveStorage.GoogleFilesMimeTypes.TryGetValue(driveFile.MimeType, out mimeData)) { ext = mimeData.Item1; } return Global.ReplaceInvalidCharsAndTruncate(driveFile.Title + ext); }
protected String MakeFolderTitle(DriveFile driveFolder) { if (driveFolder == null || IsRoot(driveFolder)) { return GoogleDriveProviderInfo.CustomerTitle; } return Global.ReplaceInvalidCharsAndTruncate(driveFolder.Title); }
protected string MakeId(DriveFile driveEntry) { var path = string.Empty; if (driveEntry != null) { path = IsRoot(driveEntry) ? "root" : driveEntry.Id; } return MakeId(path); }
public File GetNewFile(string title, string target) { char separator = '\\'; //System.IO.Path.DirectorySeparatorChar; string parent = target.Substring(0, target.IndexOf(separator)); Google.Apis.Drive.v2.Data.File file = new Google.Apis.Drive.v2.Data.File(); file.Title = title; file.Description = "Google Drive Downloader"; file.MimeType = GetMimeType(title); file.Parents = new List<Google.Apis.Drive.v2.Data.ParentReference>() { new Google.Apis.Drive.v2.Data.ParentReference() { Id = parent } }; return new GDriveFile(file); }
public File ToFile(DriveFile driveFile) { if (driveFile == null) return null; if (driveFile is ErrorDriveEntry) { //Return error entry return ToErrorFile(driveFile as ErrorDriveEntry); } return new File { ID = MakeId(driveFile.Id), Access = FileShare.None, ContentLength = driveFile.FileSize.HasValue ? (long)driveFile.FileSize : 0, CreateBy = GoogleDriveProviderInfo.Owner, CreateOn = driveFile.CreatedDate.HasValue ? TenantUtil.DateTimeFromUtc(driveFile.CreatedDate.Value) : default(DateTime), FileStatus = FileStatus.None, FolderID = MakeId(GetParentDriveId(driveFile)), ModifiedBy = GoogleDriveProviderInfo.Owner, ModifiedOn = driveFile.ModifiedDate.HasValue ? TenantUtil.DateTimeFromUtc(driveFile.ModifiedDate.Value) : default(DateTime), NativeAccessor = driveFile, ProviderId = GoogleDriveProviderInfo.ID, ProviderKey = GoogleDriveProviderInfo.ProviderKey, Title = MakeFileTitle(driveFile), RootFolderId = MakeId(), RootFolderType = GoogleDriveProviderInfo.RootFolderType, RootFolderCreator = GoogleDriveProviderInfo.Owner, SharedByMe = false, Version = 1 }; }
public IHttpActionResult PostUploadFiles(FileBase fileBase) { try { HttpPostedFileBase theFile = fileBase.PostedFileBase; if (theFile.ContentLength != 0) { var objFile = new Dms(); var file = new File(); var buffer = new byte[theFile.ContentLength]; fileBase.PostedFileBase.InputStream.Read(buffer, 0, fileBase.PostedFileBase.ContentLength); var stream = new System.IO.MemoryStream(buffer); MemoryStream objFile1 = new MemoryStream(); file = objFile.FileUpload(ConfigurationManager.AppSettings["ClientId"], ConfigurationManager.AppSettings["Clientsecret"], theFile.FileName, theFile.FileName, theFile.ContentType, stream, ConfigurationManager.ConnectionStrings["BPM"].ToString() ); if (file != null) { //ObjCPService.FileTableInsert(new CPservice.ecubeDocument //{ // ParentCode = guId, // // ParentCode = "",// replace with shipment No // DateCreated = DateTime.Now, // DocType = Request.QueryString["DocType"], // DocName = Request.QueryString["DocDesc"], // DocumentURL = file.DownloadUrl, // DocReferenceID = file.Id, // FileName = file.OriginalFilename.Substring(file.OriginalFilename.LastIndexOf("\\") + 1), // //FileContentBytes = buffer, // FileExtension = file.FileExtension, // UploadedBy = Session["EmailId"].ToString(), //Session["UserId"].ToString(), // PublicViewable = "Y", // ParentSystem = "CP",//eCube // ParentSource = "Shipment", // ContentType = file.FileExtension, // SizeInKB = Convert.ToInt64(Math.Round(ConvertBytesToMegabytes(Convert.ToInt64(file.FileSize)), 4)) //}); var documents = new eDrive_Document { DocCode = "", FileName = file.OriginalFilename, FileExtension = file.FileExtension, SizeinKb = Convert.ToInt64(Math.Round(ConvertBytesToMegabytes(Convert.ToInt64(file.FileSize)), 4)), ContentType = file.FileExtension, IsPublic = true, IsAuto = true, IsDeleted = false, ParentSystem = fileBase.ParentSystem, ParentSource = fileBase.ParentSource, ParentCode= "Parent Code", IsQuarantine=true, GoogleReferenceId = file.Id, GoogleURL = file.DownloadUrl, CreatedBy = "Admin", CreatedDate=DateTime.Now, ModifiedBy="Admin", DateModified = DateTime.Now }; _db.eDrive_Document.Add(documents); _db.SaveChanges(); } } return Ok(); } catch (Exception e) { throw e; } }
protected void CacheInsert(DriveFile driveEntry) { CacheEntry.Add(GoogleDriveProviderInfo.ID + driveEntry.Id, driveEntry); }
public GDriveFile(Google.Apis.Drive.v2.Data.File item) { this.item = item; }
public GoogleDriveFile(GoogleDriveStorage storage, GoogleDriveDirectory parent, Google.Apis.Drive.v2.Data.File file) { this.storage = storage; this.parent = parent; this.file = file; }