public async Task <string> uploadFileGoogledrivetoweb(DriveService _service, byte[] byteArray, string _uploadFile, string _parent = "") { if (true || System.IO.File.Exists(_uploadFile)) { Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File(); body.Title = System.IO.Path.GetFileName(_uploadFile); body.Description = "File Name " + DateTime.Now.ToString(); body.MimeType = GetMimeType(_uploadFile); // body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } }; // uploadFileGoogledrive(_service, _uploadFile); // File's content. byte[] buffer = System.IO.File.ReadAllBytes(_uploadFile); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile)); request.Upload(); await Task.Delay(1000); return("pass File Uploaded"); } catch (Exception e) { return("fail" + e.Message); } } else { return("File does not exist: " + _uploadFile); } }
internal static File UploadFile(DriveService service, System.IO.Stream fileStream, string title, string description, string parent, params Property[] properties) { File body = new File() { Title = title, MimeType = "application/unknown", Parents = new List <ParentReference>() { new ParentReference() { Id = parent } }, Description = description, Properties = new List <Property>() }; foreach (var property in properties) { body.Properties.Add(property); } fileStream.Seek(0, System.IO.SeekOrigin.Begin); FilesResource.InsertMediaUpload request = service.Files.Insert(body, fileStream, body.MimeType); request.Upload(); return(request.ResponseBody); }
public File UploadFile(DriveService _service, ExportData _uploadFile) { File body = new File(); body.Title = _uploadFile.FileName; body.Description = "File uploaded by Diamto Drive Sample"; body.MimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; body.Parents = new List <ParentReference>() { new ParentReference() { Id = _uploadFile.Folder } }; System.IO.MemoryStream stream = new System.IO.MemoryStream(_uploadFile.Data); try { FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, body.MimeType); request.Upload(); return(request.ResponseBody); } catch (Exception e) { return(null); } }
//Paso 5 Carga el o los archivos a la nube public static Google.Apis.Drive.v2.Data.File uploadFile(DriveService _service, string _uploadFile, string _parent) { if (System.IO.File.Exists(_uploadFile)) { Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File(); body.Title = System.IO.Path.GetFileName(_uploadFile); body.Description = "Achivo subido por un programa externo"; body.MimeType = GetMimeType(_uploadFile); body.Parents = new List <ParentReference>() { new ParentReference() { Id = _parent } }; // File's content. byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile)); request.Upload(); return(request.ResponseBody); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return(null); } } else { Console.WriteLine("File does not exist: " + _uploadFile); return(null); } }
public void saveNotes(string noteHtml) { File parentFolder = getScrumNotesFolder(); parentFolder = getScrumNotesFolder(); // TODO: getScrumNotesFolder returns null when the folder didn't exist to start Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File(); body.Title = ScrumNotesFileName; body.Description = ScrumNotesFileName; body.MimeType = "text/html"; body.Parents = new List <ParentReference>() { new ParentReference() { Id = parentFolder.Id } }; System.IO.MemoryStream stream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(noteHtml ?? "")); FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/html"); request.Convert = true; 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 string f_uploadFile(DriveFile df) { if (this._authenticator == null || this._driveService == null) { return(JsonConvert.SerializeObject(new { Ok = false, tokenAccess = this._token, File = df, Message = "redirect user to authentication" })); } try { // File's metadata. Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File(); body.Title = df.title; body.Description = df.description; body.MimeType = df.mimeType; byte[] byteArray = Encoding.ASCII.GetBytes(df.content); MemoryStream stream = new MemoryStream(byteArray); FilesResource.InsertMediaUpload request = this._driveService.Files.Insert(body, stream, df.mimeType); request.Upload(); Google.Apis.Drive.v2.Data.File file = request.ResponseBody; Permission newPermission = new Permission(); newPermission.Type = "anyone"; newPermission.Role = "reader"; newPermission.Value = ""; newPermission.WithLink = true; this._driveService.Permissions.Insert(newPermission, file.Id).Fetch(); return(JsonConvert.SerializeObject(new { Ok = false, tokenAccess = this._token, File = new DriveFile(file, df.content) })); } catch (Exception e) { return(JsonConvert.SerializeObject(new { Ok = false, tokenAccess = this._token, Message = e.Message, File = df })); } }
/// <summary> /// Uploads a file /// Documentation: https://developers.google.com/drive/v2/reference/files/insert /// </summary> /// <param name="service">a Valid authenticated DriveService</param> /// <param name="uploadFile">path to the file to upload</param> /// <param name="parentIdFolder">Collection of parent folders which contain this file. /// Setting this field will put the file in all of the provided folders. root folder.</param> /// <returns>If upload succeeded returns the File resource of the uploaded file /// If the upload fails returns null</returns> public static File UploadFile(DriveService service, string uploadFile, string parentIdFolder) { if (System.IO.File.Exists(uploadFile)) { File body = new File { Title = Path.GetFileName(uploadFile), Description = "File uploaded", MimeType = GetMimeType(uploadFile), Parents = new List <ParentReference> { new ParentReference { Id = parentIdFolder } } }; // File's content. byte[] byteArray = System.IO.File.ReadAllBytes(uploadFile); MemoryStream stream = new MemoryStream(byteArray); try { FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, GetMimeType(uploadFile)); request.Upload(); return(request.ResponseBody); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return(null); } } Console.WriteLine("File does not exist: " + uploadFile); return(null); }
public static File UploadFile(DriveService service, byte[] byteArr, string parent) { File body = new File { Title = "NewImage", MimeType = "image/jpg", Parents = new List <ParentReference>() { new ParentReference() { Id = parent } } }; System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArr); try { FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "image/jpg"); request.Upload(); return(request.ResponseBody); } catch (Exception e) { Console.WriteLine(UploadUnsuccessful + e.Message); return(null); } }
public static String /*File*/ uploadFile(DriveService service, string localFilePath) { if (System.IO.File.Exists(localFilePath)) { //File's body File body = new File(); body.Title = System.IO.Path.GetFileName(localFilePath); body.Description = "Uploaded by Popcorn-GDrive"; body.MimeType = GetMimeType(localFilePath); //File content byte[] byteArray = System.IO.File.ReadAllBytes(localFilePath); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, GetMimeType(localFilePath)); request.Upload(); //String fileID = request.ResponseBody.Id; return(request.ResponseBody.Id); } catch (Exception e) { throw; } } else { return(null); } }
// ... /// <summary> /// Insert new file. /// </summary> /// <param name="service">Drive API service instance.</param> /// <param name="title">Title of the file to insert, including the extension.</param> /// <param name="description">Description of the file to insert.</param> /// <param name="parentId">Parent folder's ID.</param> /// <param name="mimeType">MIME type of the file to insert.</param> /// <param name="filename">Filename of the file to insert.</param> /// <returns>Inserted file metadata, null is returned if an API error occurred.</returns> private static File insertFile(DriveService service, String title, String description, String parentId, String mimeType, String filename) { // File's metadata. File body = new File(); body.Title = title; body.Description = description; body.MimeType = mimeType; // Set the parent folder. if (!String.IsNullOrEmpty(parentId)) { body.Parents = new List<ParentReference>() {new ParentReference() {Id = parentId}}; } // File's content. byte[] byteArray = System.IO.File.ReadAllBytes(filename); MemoryStream stream = new MemoryStream(byteArray); try { FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType); request.Upload(); File file = request.ResponseBody; // Uncomment the following line to print the File ID. // Console.WriteLine("File ID: " + file.Id); return file; } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return null; } }
static void Main(string[] args) { String CLIENT_ID = "YOUR_CLIENT_ID"; String CLIENT_SECRET = "YOUR_CLIENT_SECRET"; // Register the authenticator and create the service var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET); var auth = new OAuth2Authenticator <NativeApplicationClient>(provider, GetAuthorization); var service = new DriveService(auth); File body = new File(); body.Title = "My document"; body.Description = "A test document"; body.MimeType = "text/plain"; byte[] byteArray = System.IO.File.ReadAllBytes("document.txt"); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain"); request.Upload(); File file = request.ResponseBody; Console.WriteLine("File id: " + file.Id); }
private static void UploadFile(DriveService service) { Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File(); body.Title = "test upload"; body.Description = "test upload"; body.MimeType = "application/vnd.ms-excel"; // GoogleFile's content. byte[] byteArray = System.IO.File.ReadAllBytes(@"C:\Users\Jasarsoft\Google Drive\Private\Expense\Boravak - Mostar.xlsx"); MemoryStream stream = new MemoryStream(byteArray); try { FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "application/vnd.google-apps.spreadsheet"); request.Upload(); Google.Apis.Drive.v2.Data.File file = request.ResponseBody; // Uncomment the following line to print the GoogleFile ID. // Console.WriteLine("GoogleFile ID: " + file.Id); } catch (Exception e) { MessageBox.Show(e.Message); //Console.WriteLine("An error occurred: " + e.Message); } }
/// <summary> /// 上傳檔案 /// </summary> /// <param name="uploadFileName">上傳的檔案名稱 </param> /// <param name="contentType">上傳的檔案種類,請參考MIME Type : http://www.iana.org/assignments/media-types/media-types.xhtml </param> /// <param name="uploadProgressEventHandler"> 上傳進度改變時呼叫的函式</param> /// <param name="responseReceivedEventHandler">收到回應時呼叫的函式 </param> /// <returns>上傳成功,回傳上傳成功的 Google Drive 格式之File</returns> public async Task <Google.Apis.Drive.v2.Data.File> UploadFile(string uploadFileName, string contentType, Action <IUploadProgress> uploadProgressEventHandler = null, Action <Google.Apis.Drive.v2.Data.File> responseReceivedEventHandler = null) { StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(uploadFileName); Stream uploadStream = await file.OpenStreamForReadAsync(); string title = SubstractFileName(uploadFileName); this.CheckCredentialTimeStamp(); Google.Apis.Drive.v2.Data.File fileToInsert = new Google.Apis.Drive.v2.Data.File { Title = title }; FilesResource.InsertMediaUpload insertRequest = _service.Files.Insert(fileToInsert, uploadStream, contentType); insertRequest.ChunkSize = FilesResource.InsertMediaUpload.MinimumChunkSize * 2; AddUploadEventHandler(uploadProgressEventHandler, responseReceivedEventHandler, insertRequest); try { insertRequest.Upload(); } catch (Exception e) { ShowMessage(e.Message); } finally { uploadStream.Dispose(); } return(insertRequest.ResponseBody); }
public void Main(string CLIENT_ID, string CLIENT_SECRET) { // Register the authenticator and create the service var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET); var auth = new OAuth2Authenticator <NativeApplicationClient>(provider, GetAuthorization); var service = new DriveService(new BaseClientService.Initializer() { Authenticator = auth }); File body = new File(); body.Title = "My document.txt"; body.Description = "A test document"; body.MimeType = "text/plain"; byte[] byteArray = Encoding.UTF8.GetBytes("Hello world!!"); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain"); request.Upload(); if (request.ResponseBody == null) { return; } var id = request.ResponseBody.Id; Console.WriteLine("File id: " + id); Console.WriteLine("Press Enter to end this process."); //Console.ReadLine(); }
public string UploadFile(string uploadDirectory, string fileName) { string fileType = "image/jpg"; File body = new File() { Title = fileName, MimeType = fileType, Parents = new List <ParentReference>() { this.cloudFolder } }; var fileinfo = System.IO.Path.Combine(uploadDirectory, fileName); byte[] byteArray = System.IO.File.ReadAllBytes(fileinfo); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); FilesResource.InsertMediaUpload request = this.service.Files.Insert(body, stream, fileType); request.Upload(); File file = request.ResponseBody; return(file.Id); }
public static string uploadFile(DriveService _service, string _uploadFile, string _parent, string _descrp = "Automatski generirani fajl.") { Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File(); body.Title = System.IO.Path.GetFileName(_uploadFile); body.Description = _descrp; body.MimeType = GetMimeType(_uploadFile); var stream = new System.IO.FileStream(_uploadFile, System.IO.FileMode.Open, System.IO.FileAccess.Read); TotalSize = stream.Length; FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile)); request.ProgressChanged += UploadProgessEvent; request.ChunkSize = FilesResource.InsertMediaUpload.MinimumChunkSize; // Minimum ChunkSize allowed by Google is 256*1024 bytes. ie 256KB. var test = request.Upload(); if (test.Exception == null) { return(null); } else { return(test.Exception.Message); } }
/// <summary> /// 上傳檔案 /// </summary> /// <param name="uploadFileName">上傳的檔案名稱 </param> /// <param name="contentType">上傳的檔案種類,請參考MIME Type : http://www.iana.org/assignments/media-types/media-types.xhtml </param> /// <param name="uploadProgressEventHandler"> 上傳進度改變時呼叫的函式</param> /// <param name="responseReceivedEventHandler">收到回應時呼叫的函式 </param> /// <returns>上傳成功,回傳上傳成功的 Google Drive 格式之File</returns> public Google.Apis.Drive.v2.Data.File UploadFile(string uploadFileName, string contentType, Action <IUploadProgress> uploadProgressEventHandler = null, Action <Google.Apis.Drive.v2.Data.File> responseReceivedEventHandler = null) { FileStream uploadStream = new FileStream(uploadFileName, FileMode.Open, FileAccess.Read); string title = SubstractFileName(uploadFileName); this.CheckCredentialTimeStamp(); Google.Apis.Drive.v2.Data.File fileToInsert = new Google.Apis.Drive.v2.Data.File { Title = title }; FilesResource.InsertMediaUpload insertRequest = _service.Files.Insert(fileToInsert, uploadStream, contentType); insertRequest.ChunkSize = FilesResource.InsertMediaUpload.MinimumChunkSize * 2; AddUploadEventHandler(uploadProgressEventHandler, responseReceivedEventHandler, insertRequest); try { insertRequest.Upload(); } catch (Exception exception) { ShowMessage(exception.Message.ToString()); throw exception; } finally { uploadStream.Close(); } return(insertRequest.ResponseBody); }
public Google.Apis.Drive.v2.Data.File InsertFile(String title, String description, String parentId, String mimeType, FileInfo filename) { Google.Apis.Drive.v2.Data.File gooleFile = new Google.Apis.Drive.v2.Data.File(); gooleFile.Title = title; gooleFile.Description = description; gooleFile.MimeType = mimeType; gooleFile.Shared = true; gooleFile.Editable = true; if (!String.IsNullOrEmpty(parentId)) { gooleFile.Parents = new List <ParentReference>() { new ParentReference() { Id = parentId } }; } byte[] byteArray = System.IO.File.ReadAllBytes(filename.FullName); using (MemoryStream stream = new MemoryStream(byteArray)) { FilesResource.InsertMediaUpload request = GoogleService.GetInstance().Service(this.m_User).Files.Insert(gooleFile, stream, mimeType); request.Upload(); return(request.ResponseBody); } }
public static Google.Apis.Drive.v2.Data.File UploadFile(DriveService _service, string _uploadFile, string _parent) { GException = null; if (System.IO.File.Exists(_uploadFile)) { Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File { Title = System.IO.Path.GetFileName(_uploadFile), Description = "File uploaded by " + Application.ProductName, MimeType = GetMimeType(_uploadFile), Parents = new List <ParentReference>() { new ParentReference() { Id = _parent } } }; byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile)); request.Upload(); return(request.ResponseBody); } catch (Exception ex) { GException = ex; return(null); } } else { GException = new Exception("File does not exist: " + _uploadFile); return(null); } }
public string UploadFile(string parentDir, string filePath, string fileName) { var mime = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; File body = new File(); body.Title = fileName; body.Description = "Kawaldesa file"; body.MimeType = mime; body.Parents = new List <ParentReference>() { new ParentReference() { Id = parentDir } }; byte[] byteArray = System.IO.File.ReadAllBytes(filePath); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); FilesResource.InsertMediaUpload request = driveService.Files.Insert(body, stream, mime); request.Convert = true; var progress = AsyncHelpers.RunSync(request.UploadAsync); return(request.ResponseBody.Id); }
//Creates JSON file on GDrive if one doesn't exist or if 1st run public static void CreateJSONonDrive() { GetCred(); // File's metadata. Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File(); body.Title = "ATGEntries.json"; body.Description = "Database JSON for Adventurer's Tour Guide"; body.MimeType = "application/json"; body.Parents = new List <ParentReference>() { new ParentReference() { Id = "Root" } }; // File's content. byte[] byteArray = System.IO.File.ReadAllBytes(Path + "\\ATGEntries.json"); MemoryStream stream = new MemoryStream(byteArray); try { FilesResource.InsertMediaUpload request = mService.Files.Insert(body, stream, "application/json"); request.Upload(); Google.Apis.Drive.v2.Data.File file = request.ResponseBody; // Uncomment the following line to print the File ID. Console.WriteLine("File ID: " + file.Id); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } }
public async Task <Google.Apis.Drive.v2.Data.File> UploadFile(string uploadFileName, string contentType, Action <IUploadProgress> uploadProgressEventHandler = null, Action <Google.Apis.Drive.v2.Data.File> responseReceivedEventHandler = null)//上傳檔案 { Windows.Storage.StorageFolder folder = ApplicationData.Current.LocalFolder; StorageFile file = await folder.GetFileAsync(uploadFileName); IRandomAccessStream readStream = await file.OpenReadAsync(); Stream uploadStream = readStream.AsStream(); string title = uploadFileName; this.CheckCredentialTimeStamp(); Google.Apis.Drive.v2.Data.File fileToInsert = new Google.Apis.Drive.v2.Data.File { Title = title }; FilesResource.InsertMediaUpload insertRequest = _service.Files.Insert(fileToInsert, uploadStream, contentType); insertRequest.ChunkSize = FilesResource.InsertMediaUpload.MinimumChunkSize * DOUBLE; AddUploadEventHandler(uploadProgressEventHandler, responseReceivedEventHandler, insertRequest); try { insertRequest.Upload(); } catch (Exception exception) { throw exception; } finally { uploadStream.Dispose(); } return(insertRequest.ResponseBody); }
/// <summary> /// Creates the files for the very first time on Google Drive /// </summary> /// <param name="title">Title of the Document.</param> /// <param name="contents">Document's body.</param> /// <returns></returns> public static bool createFile(string title, string contents) { try { Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File(); body.Title = title; body.Description = "Uploaded from Google Docs Desktop Utility."; body.MimeType = "text/plain"; //byte[] byteArray = System.IO.File.ReadAllBytes("document.txt"); byte[] byteArray = System.Text.Encoding.Unicode.GetBytes(contents); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain"); FilesResource filesResource = service.Files; FilesResource.ListRequest listRequest = filesResource.List(); request.Upload(); currentJobFile = request.ResponseBody; return(true); } catch (Exception) { return(false); } }
public async Task <ActionResult> UploadAsync(CancellationToken cancellationToken, ExamPaperViewModel model) { var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(cancellationToken); if (result.Credential != null) { if ((TempData["isInitialPost"] != null) && (bool)TempData["isInitialPost"]) { model = (ExamPaperViewModel)TempData["examViewModel"]; TempData.Remove("examViewModel"); TempData.Remove("isInitialPost"); } var service = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = result.Credential, ApplicationName = ApplicationName }); var file = new File() { Title = model.UploadFile.FileName, MimeType = model.UploadFile.ContentType }; try { FilesResource.InsertMediaUpload uploadRequest = service.Files.Insert(file, model.UploadFile.InputStream, file.MimeType); uploadRequest.ChunkSize = 256 * 1024; var awList = await uploadRequest.UploadAsync(); var uploadResponse = uploadRequest.ResponseBody; var examDetails = new { PaperName = model.PaperName, SubjectId = model.SelectedSubject, GradeId = model.SelectedGrade, Year = model.Year.ToString(), HasAnswers = model.HasAnswers, FileStoreId = uploadResponse.Id }; var createFileResponse = HttpDataProvider.PostAndReturn <dynamic, dynamic>("exam/create", examDetails); } catch (Exception ex) { // Todo: Log errors and show friendly error } model = assignGradesAndSubjectsListToModel(model); return(View("Index", model)); } else { TempData.Add("examViewModel", model); TempData.Add("isInitialPost", true); return(new RedirectResult(result.RedirectUri)); } }
public File UploadFile(Initializer initializer, File file, System.IO.MemoryStream stream, String fileExtension) { DriveService svc = new DriveService(CreateInitializer(initializer)); file.MimeType = GetMimeType(fileExtension); FilesResource.InsertMediaUpload request = svc.Files.Insert(file, stream, GetMimeType(fileExtension)); request.Upload(); return(request.ResponseBody); }
public File CreateFile(File file, string data) { file.MimeType = "text/plain"; byte[] byteArray = Encoding.ASCII.GetBytes(data); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); FilesResource.InsertMediaUpload request = drive.Files.Insert(file, stream, "text/plain"); request.Upload(); return(request.ResponseBody); }
static void Main() { var certificate = new X509Certificate2(Key, "notasecret", X509KeyStorageFlags.Exportable); var initializer = new ServiceAccountCredential.Initializer(ServiceAccountEmail) { Scopes = new[] { DriveService.Scope.Drive }, User = ImpersonatedAccountEmail }; var credential = new ServiceAccountCredential(initializer.FromCertificate(certificate)); var driveService = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName }); // Show all files var list = driveService.Files.List().Execute(); if (list.Items != null) { foreach (var fileItem in list.Items) { Console.WriteLine(fileItem.Title + " - " + fileItem.Description); } } Console.WriteLine("Press Enter to continue."); Console.ReadLine(); // Upload a new file File body = new File(); body.Title = "whakingly.txt"; body.Description = "A whakingly (that a new word I created just there) file thats uploaded with impersonation"; body.MimeType = "text/plain"; byte[] byteArray = System.IO.File.ReadAllBytes(FileToUpload); var stream = new System.IO.MemoryStream(byteArray); FilesResource.InsertMediaUpload request = driveService.Files.Insert(body, stream, "text/plain"); request.Upload(); File file = request.ResponseBody; Console.WriteLine("Press Enter to continue."); Console.ReadLine(); // Show all files var list2 = driveService.Files.List().Execute(); if (list2.Items != null) { foreach (var fileItem in list2.Items) { Console.WriteLine(fileItem.Title + " - " + fileItem.Description); } } Console.WriteLine("Press Enter to continue."); Console.ReadLine(); }
protected override async void StreamThread() { if (System.IO.File.Exists(this.filename)) { File body = new File(); long contentlong = 0; label.Text = "0%"; label.Name = "label"; label.AutoSize = true; progress.Value = 0; progress.Maximum = 100; progress.Controls.Add(label); progress.Size = new System.Drawing.Size(181, 23); body.Title = System.IO.Path.GetFileName(this.filename); body.Description = "File uploaded by 클라우드 통합관리"; body.MimeType = DaimtoGoogleDriveHelper.GetMimeType(this.filename); body.Parents = new List <ParentReference>() { new ParentReference() { Id = this.Parent } }; FilesResource.InsertMediaUpload request = null; this.OnControl(this, progress, label); byte[] byteArray = new byte[this.StreamBlockSize]; int ReadSize = 0; System.IO.MemoryStream mstream = new System.IO.MemoryStream(); try { while ((ReadSize = await realfile.ReadAsync(byteArray, 0, this.StreamBlockSize, CancellationToken.None)) > 0) { mstream.Capacity = ReadSize; contentlong += ReadSize; request = this.service.Files.Insert(body, mstream, DaimtoGoogleDriveHelper.GetMimeType(this.filename)); this.OnProgressChange(this, maxsize, contentlong, this.progress); } request.Upload(); realfile.Close(); mstream.Close(); this.OnComplete(this, progress); } catch (Exception e) { MessageBox.Show("오류: " + e.Message); return; } } else { MessageBox.Show("파일이 존재하지 않습니다: " + this.filename); return; } }
/// <summary> /// Insert new file. /// </summary> /// <param name="service">Drive API service instance.</param> /// <param name="title">Title of the file to insert, including the extension.</param> /// <param name="description">Description of the file to insert.</param> /// <param name="parentId">Parent folder's ID.</param> /// <param name="mimeType">MIME type of the file to insert.</param> /// <param name="filename">Filename of the file to insert.</param><br> /// <returns>Inserted file metadata, null is returned if an API error occurred.</returns> public GoogleDriveFile insertFile(String title, String description, String mimeType, String filename) { // File's metadata. File body = new File(); body.Title = title; body.Description = description; body.MimeType = mimeType; // Set the parent folder. String directoryId = GetParentId(); if (!String.IsNullOrEmpty(directoryId)) { body.Parents = new List <ParentReference>() { new ParentReference() { Id = directoryId } }; } // File's content. byte[] byteArray = System.IO.File.ReadAllBytes(filename); var stream = new System.IO.MemoryStream(byteArray); try { FilesResource.InsertMediaUpload request = Service.Files.Insert(body, stream, mimeType); request.Upload(); File file = request.ResponseBody; // Uncomment the following line to print the File ID. // Console.WriteLine("File ID: " + file.Id); if (file == null) { throw new Exception("InsertMediaUpload request.ResponseBody is null"); } else { return(ConvertFileToGoogleDriveFile(file)); } } catch (Exception e) { Logger.Error(e, "GoogleDriveFile InsertFile An error occurred: " + e.StackTrace, title, description, mimeType, filename); return(null); } }
public GoogleDriveFile UploadFile( string uploadFile, String description = "File uploaded by DriveUploader For Windows") { if (System.IO.File.Exists(uploadFile)) { String directoryId = GetParentId(); var body = new File { Title = System.IO.Path.GetFileName(uploadFile), Description = description, MimeType = GetMimeType(uploadFile), Parents = new List <ParentReference>() { new ParentReference() { Id = directoryId } } }; byte[] byteArray = System.IO.File.ReadAllBytes(uploadFile); var stream = new System.IO.MemoryStream(byteArray); try { //body.UserPermission.WithLink = true; //body.UserPermission.Type = "anyone"; FilesResource.InsertMediaUpload request = Service.Files.Insert(body, stream, GetMimeType(uploadFile)); request.Upload(); var file = request.ResponseBody; if (file == null) { throw new Exception("InsertMediaUpload request.ResponseBody is null"); } else { return(ConvertFileToGoogleDriveFile(file)); } } catch (Exception e) { Logger.Error("An error occurred: " + e.Message, e); return(null); } } else { Logger.Error("File does not exist: " + uploadFile); return(null); } }