private async Task <bool> UploadToGoogleDrive(DriveService service, string fileToUpload, string parentId)
        {
            await RemoveExistingFileIfExists(service, fileToUpload, parentId).ConfigureAwait(false);

            await using Stream fileToUploadStream = new FileStream(
                            fileToUpload, FileMode.Open, FileAccess.Read, FileShare.None, 4096, useAsync: true);

            GoogleData.File fileMetadata = new GoogleData.File()
            {
                Name    = fileToUpload,
                Parents = new string[] { parentId }
            };

            FilesResource.CreateMediaUpload createRequest =
                service.Files.Create(fileMetadata, fileToUploadStream, null);
            createRequest.Fields = "id";

            IUploadProgress uploadProgress = await createRequest.UploadAsync().ConfigureAwait(false);

            if (uploadProgress.Status != UploadStatus.Completed)
            {
                mLogger.LogWarning($"Uploaded {fileToUpload} to {mTaskerDriveDirectory}. " +
                                   $"Bytes: {uploadProgress.BytesSent}. Status: {uploadProgress.Status}");
                return(false);
            }

            mLogger.LogDebug($"Uploaded {fileToUpload} to {mTaskerDriveDirectory}. " +
                             $"Bytes: {uploadProgress.BytesSent}. Status: {uploadProgress.Status}");

            return(true);
        }
Example #2
0
        private async void uploadFileProcess(string path)
        {
            btnUpload.Enabled = false;
            this.AllowDrop    = false;
            try
            {
                System.IO.FileInfo fI = new System.IO.FileInfo(path);
                uploadfilesize = fI.Length;
                FilesResource.CreateMediaUpload request = gd.uploadFile(service, path, "");
                request.Fields           = "id";
                request.ProgressChanged += Request_ProgressChanged;
                FileItemUpload fileItemUpload = new FileItemUpload();
                fileItemUpload.name.Text = System.IO.Path.GetFileName(path).ToString();
                fileItemUpload.fileIcon.BackgroundImage = misc.getFileIcon(misc.getFileExtention(System.IO.Path.GetFileName(path).ToString()));
                fileItemUpload.size.Text = ByteSize.FromBytes((double)fI.Length).ToString();
                progressBar = fileItemUpload.progress;
                flpMain.Controls.Add(fileItemUpload);
                flpMain.Controls.SetChildIndex(fileItemUpload, 0);
                timer1.Enabled = true;
                timer1.Start();
                await request.UploadAsync();

                gd.filePermission("anyone", request.ResponseBody.Id);
            } catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                btnUpload.Enabled = true;
                this.AllowDrop    = true;
            }
        }
Example #3
0
 public Google.Apis.Drive.v3.Data.File uploadFile(DriveService _service, string _uploadFile, string _parent, string _descrp = "Uploaded with .NET!")
 {
     if (System.IO.File.Exists(_uploadFile))
     {
         Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();
         body.Name        = System.IO.Path.GetFileName(_uploadFile);
         body.Description = _descrp;
         body.MimeType    = GetMimeType(_uploadFile);
         body.Parents     = new List <string> {
             _parent
         };                                         // 폴더에 업로드하려면 UN 주석 (위의 방법에서 상위 폴더의 ID를 매개 변수로 보내야 함)
         byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
         System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
         try
         {
             FilesResource.CreateMediaUpload request = _service.Files.Create(body, stream, GetMimeType(_uploadFile));
             request.SupportsTeamDrives = true;
             // 진행 변경 이벤트 및 응답 수신 (완료된 이벤트)으로 이벤트 핸들러를 바인딩 할 수 있습니다.
             request.ProgressChanged  += Request_ProgressChanged;
             request.ResponseReceived += Request_ResponseReceived;
             request.UploadAsync();
             return(request.ResponseBody);
         }
         catch (Exception e)
         {
             Console.WriteLine("Error: " + e.Message);
             return(null);
         }
     }
     else
     {
         MessageBox.Show("파일이 없습니다.", "404");
         return(null);
     }
 }
Example #4
0
        public async Task ResumableChunkUpload(string filePath)
        {
            using (var client = DriveClient.GetInfo())
            {
                try
                {
                    FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    FilesResource.CreateMediaUpload request = new FilesResource.CreateMediaUpload(client,
                                                                                                  new Google.Apis.Drive.v3.Data.File
                    {
                        Name    = "new File",
                        Parents = new List <string>()
                        {
                            "1K46j8qE2sOiFAMNvSz21xFxgpVTYlcWm"
                        },
                    },
                                                                                                  stream,
                                                                                                  "video/mpeg4");
                    request.ChunkSize = 1024 * 1024;
                    await request.InitiateSessionAsync();

                    Task <Google.Apis.Upload.IUploadProgress> uploadTask = request.UploadAsync();
                    for (var i = 0; i < 1000; i++)
                    {
                        System.Threading.Thread.Sleep(1000);
                        Console.WriteLine(request.GetProgress().BytesSent);
                    }
                    await uploadTask;
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message + " " + e.StackTrace);
                }
            }
        }
    public async void Upload(DriveService svc)
    {
        Google.Apis.Drive.v3.Data.File body = new File();
        body.Name     = fileName;
        body.MimeType = mimeType;
        body.Parents  = new List <string>();
        body.Parents.Add(directoryID);
        FilesResource.CreateMediaUpload req = svc.Files.Create(body, _stream, mimeType);
        req.Fields            = "id, parents";
        req.ResponseReceived += ReqOnResponseReceived;

        var result = await req.UploadAsync();
    }
        public static async Task <IUploadProgress> UploadFile(string uploadFile, Dictionary <string, string> appFileAttributes = null)
        {
            IsUploadingFile = true;
            DriveService    service  = GetGDriveService();
            IUploadProgress progress = null;

            //Task<IUploadProgress> progress = null;
            if (System.IO.File.Exists(uploadFile))
            {
                File body = new File();
                body.Name        = Path.GetFileName(uploadFile);
                _uploadFilename  = body.Name;
                body.Description = FileUploadDescription;
                body.Properties  = appFileAttributes;
                body.MimeType    = GetMimeType(uploadFile);
                //body.Id = DateTime.Now.ToString("dd-HH:mm:ss.fffff");


                try
                {
                    // File's content.
                    byte[]       byteArray = System.IO.File.ReadAllBytes(uploadFile);
                    MemoryStream stream    = new MemoryStream(byteArray);

                    //FilesResource.UpdateMediaUpload uploadRequest = service.Files.Update(f, "", stream, body.MimeType);
                    FilesResource.CreateRequest cr = service.Files.Create(body);
                    File f = cr.Execute();
                    //FilesResource.CreateMediaUpload uploadRequest = service.Files.Create(f, stream, body.MimeType);
                    //uploadRequest.Body.Id = DateTime.Now.ToString("dd-HH:mm:ss.fffff");
                    //body.Id = "WRJskjslkdjslj3q9";
                    FilesResource.CreateMediaUpload uploadRequest = service.Files.Create(body, stream, body.MimeType);
                    //FilesResource.CreateMediaUpload ur = new FilesResource.CreateMediaUpload(service, body, stream, body.MimeType);
                    //uploadRequest.Fields = "Id";
                    //uploadRequest.Body.Properties = new Dictionary<string, string>();
                    //uploadRequest.Body.Properties.Add("sdkjfs", "kdjskjd");
                    uploadRequest.SupportsTeamDrives = true;
                    uploadRequest.ResponseReceived  += UploadRequest_ResponseReceived;
                    uploadRequest.ProgressChanged   += UploadRequest_ProgressChanged;
                    // new Exception("Exception");
                    progress = await uploadRequest.UploadAsync();//.UploadAsync();
                }
                catch (Exception e)
                {
                    Debug.WriteLine("An error occurred: " + e.Message);
                    throw;
                }
                finally { IsUploadingFile = false; }
            }
            service?.Dispose();
            return(progress);// uploadedFile == null ? string.Empty : uploadedFile.Id;
        }
        public async Task <List <Sheaf> > UploadFile(List <Sheaf> listToUpload)
        {
            var service = AutenthicationGoogleDrive();

            long fileIdx    = 1;
            long filesCount = listToUpload.Count;

            foreach (var data in listToUpload)
            {
                File fileToUpload = new File
                {
                    Name     = data.Name,
                    MimeType = GetMimeType(data.Path),
                };

                if (data.FolderId != null && IsFolderAvaliable(service, data.FolderId))
                {
                    fileToUpload.Parents = data.Parents();
                }
                else
                {
                    string parent = ParentIdFinder(service, data);
                    data.FolderId        = parent;
                    fileToUpload.Parents = data.Parents();
                }

                byte[]       byteArray = System.IO.File.ReadAllBytes(data.Path);
                MemoryStream stream    = new MemoryStream(byteArray);

                try
                {
                    FilesResource.CreateMediaUpload request = service.Files.Create(fileToUpload, stream,
                                                                                   fileToUpload.MimeType);

                    request.ProgressChanged += (up) => _proggressReporter.ReportPartial(up.BytesSent, byteArray.Length);
                    request.ChunkSize        = FilesResource.CreateMediaUpload.MinimumChunkSize * 5;

                    await request.UploadAsync();
                }
                catch (Exception e)
                {
                    MessageBox.Show("An error occurred: " + e.Message);
                }

                _proggressReporter.ReportTotal(fileIdx++, filesCount);
            }
            return(listToUpload);
        }
Example #8
0
        public static string UploadFileDrive(string folderId, double requestNumber, WorkflowFile file)
        {
            // Check parameters
            if (string.IsNullOrEmpty(folderId))
            {
                return("The folder id is required");
            }
            if (string.IsNullOrEmpty(requestNumber.ToString()))
            {
                return("The request number is required");
            }
            if (file == null)
            {
                return("The file is required");
            }

            try
            {
                File body = new File();
                body.Name        = requestNumber + "_" + file.Name;
                body.Description = file.Name;
                body.MimeType    = file.ContentType;
                body.Parents     = new List <string> {
                    folderId
                };
                Stream stream = new MemoryStream(file.Content);

                // Insert preparation
                string[] scopes = { DriveService.Scope.DriveFile };

                var service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = GetServiceAccountCredential(scopes),
                });

                FilesResource.CreateMediaUpload request = service.Files.Create(body, stream, file.ContentType);
                request.SupportsTeamDrives = true;
                request.UploadAsync().Wait();

                return(Success);
            }
            catch (Exception e)
            {
                Log("[UploadFileDrive] Error - " + e.Message + " - InnerException : " + e.InnerException);
                return("[UploadFileDrive] Error - " + e.Message);
            }
        }
Example #9
0
        private async Task <IGoogleDriveFile> InternalUploadFileAsync(string fileName, Stream data, string contentType, string description, IDictionary <string, string> properties)
        {
            var file = new File
            {
                Name    = fileName,
                Parents = new List <string> {
                    RootId.Value.Result
                },
                Properties  = properties,
                Description = description
            };
            var uploadReq = new FilesResource.CreateMediaUpload(_driveService, file, data, contentType)
            {
                Fields             = GoogleDriveFileFieldList,
                QuotaUser          = QuotaUser,
                SupportsTeamDrives = _config.SupportsTeamDrives
            };
            Exception lastException = null;

            for (var i = 0; i <= 7; i++)
            {
                if (i != 0)
                {
                    _logger.LogInformation($"Retrying upload: {fileName}. Try # {i + 1}");
                }
                var uploadResult = await uploadReq.UploadAsync();

                lastException = uploadResult.Exception;
                if (lastException == null)
                {
                    break;
                }
                await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, i)));

                _logger.LogInformation($"Retrying upload: {fileName} in {Math.Pow(2, i)} sec");
            }
            if (lastException != null)
            {
                throw new ApplicationException(lastException.Message, lastException);
            }
            _logger.LogInformation($"Uploaded {fileName} : {uploadReq.ResponseBody.Id}");
            return(GoogleDriveFile.Create(uploadReq.ResponseBody, this));
        }
Example #10
0
        /// <summary>
        /// Realiza o upload de um arquivo
        /// </summary>
        /// <param name="nomeArquivo">Nome do arquivo com a extensão.</param>
        /// <param name="mimeType">Mime type do arquivo</param>
        /// <param name="conteudoArquivo">Conteúdo do arquivo qu será feito upload.</param>
        /// <param name="descricaoArquivo">Descrição do arquivo.</param>
        /// <param name="idPastaPai">ID da pasta onde o arquivo será armazenado.</param>
        public async Task <string> RealizarUpload(string nomeArquivo, string mimeType, byte[] conteudoArquivo, string descricaoArquivo = null, string idPastaPai = null)
        {
            var fileMetadata = new GoogleApiV3Data.File
            {
                Name        = nomeArquivo,
                Description = descricaoArquivo,
                MimeType    = mimeType,
                Parents     = !string.IsNullOrEmpty(idPastaPai) ? new List <string>()
                {
                    idPastaPai
                } : null
            };

            var stream = new MemoryStream(conteudoArquivo);

            FilesResource.CreateMediaUpload request = _driveService.Files.Create(fileMetadata, stream, mimeType);
            await request.UploadAsync();

            return(request.ResponseBody.Id);
        }
Example #11
0
        public static async Task <Google.Apis.Drive.v3.Data.File> UploadFile()
        {
            var name     = ($"{DateTime.UtcNow.ToString()}.txt");
            var mimeType = "text/plain";

            var fileMetadata = new Google.Apis.Drive.v3.Data.File()
            {
                Name     = name,
                MimeType = mimeType,
                Parents  = new[] { folderId }
            };

            FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);

            FilesResource.CreateMediaUpload request = service.Files.Create(fileMetadata, stream, mimeType);
            request.Fields = "id, name, parents, createdTime, modifiedTime, mimeType, thumbnailLink";
            await request.UploadAsync();

            return(request.ResponseBody);
        }
 public Google.Apis.Drive.v3.Data.File uploadFile(DriveService _service, string _uploadFile, string _parent, string _descrp = "Uploaded with .NET!")
 {
     if (System.IO.File.Exists(_uploadFile))
     {
         Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();
         body.Name        = System.IO.Path.GetFileName(_uploadFile);
         body.Description = _descrp;
         body.MimeType    = GetMimeType(_uploadFile);
         // UN-comment the following line if you want to upload to a folder(ID of parent folder need to be send as paramter in above method)
         //body.Parents = new List<string> { _parent };
         byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
         System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
         try
         {
             FilesResource.CreateMediaUpload request = _service.Files.Create(body, stream, GetMimeType(_uploadFile));
             request.SupportsTeamDrives = true;
             // You can bind event handler with progress changed event and response recieved(completed event)
             request.ProgressChanged  += Request_ProgressChanged;
             request.ResponseReceived += Request_ResponseReceived;
             var task = request.UploadAsync();
             task.ContinueWith(t =>
             {
                 // Remeber to clean the stream.
                 stream.Dispose();
             });
             return(request.ResponseBody);
         }
         catch (Exception e)
         {
             MessageBox.Show(e.Message, "Error Occured");
             return(null);
         }
     }
     else
     {
         MessageBox.Show("The file does not exist.", "404");
         return(null);
     }
 }
Example #13
0
        private async Task <string> UploadToDriveAsync(DriveService service, Google.Apis.Drive.v3.Data.File body, MemoryStream stream, string mimeType)
        {
            string result = "";

            try
            {
                _logger.WriteInfo("Creating upload request ");
                FilesResource.CreateMediaUpload request = service.Files.Create(body, stream, mimeType);
                _logger.WriteInfo("Uploading file to google drive");
                await request.UploadAsync();

                //_logger.WriteError(ex, "Drive exception " + ex.Message);
                result = request.ResponseBody.Id;
                _logger.WriteInfo("Result file id: " + result);
            }
            catch (Exception e)
            {
                _logger.WriteError(e, e.Message);
                throw e;
            }
            return(result);
        }
        public static FilesResource.CreateMediaUpload StartUpload(string parent, System.IO.FileInfo fileInfo, System.IO.FileStream fileStream, CancellationToken cancellationToken)
        {
            string MimeType = MimeMapping.MimeUtility.GetMimeMapping(fileInfo.Extension);

            File file = new File()
            {
                Name     = fileInfo.Name,
                MimeType = MimeType,
                Parents  = new List <string>()
                {
                    parent
                }
            };

            FilesResource.CreateMediaUpload uploadRequest = new FilesResource.CreateMediaUpload(Service, file, fileStream, MimeType)
            {
                Fields    = "id, name, ownedByMe, modifiedTime, size, mimeType",
                ChunkSize = ResumableUpload.MinimumChunkSize
            };

            uploadRequest.UploadAsync(cancellationToken);

            return(uploadRequest);
        }
Example #15
0
        public bool UploadCloudFile(FileBlock file, string destinationPath = null)
        {
            bool status = false;

            try
            {
                using (var client = DriveClient.GetInfo())
                {
                    using (var stream = new FileStream(file.path, FileMode.OpenOrCreate))
                    {
                        FilesResource.CreateMediaUpload request = new FilesResource.CreateMediaUpload(client,
                                                                                                      new Google.Apis.Drive.v3.Data.File
                        {
                            Name    = file.Name,
                            Parents = file.Parent,
                        },
                                                                                                      stream,
                                                                                                      file.mimeType);
                        request.ChunkSize = 1024 * 1024;
                        Task initiateSessionTask = Task.Run(() => request.InitiateSessionAsync());
                        initiateSessionTask.Wait();
                        Task <Google.Apis.Upload.IUploadProgress> uploadTask = Task.Run(() => request.UploadAsync());
                        uploadTask.Wait();
                        status = true;
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message + " " + e.StackTrace);
            }

            return(status);
        }
        /// <summary>
        /// dosya yükler
        /// </summary>
        /// <param name="file">yüklenecek dosya</param>
        /// <param name="parentId">hangi klasöre yüklenecek, boş geçilirse DriveApiExample klasörü oluşturup oraya yükler</param>
        /// <returns></returns>
        public async Task <Google.Apis.Drive.v3.Data.File> UploadFile(string file, string parentId = null)
        {
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(file);

            if (System.IO.File.Exists(file))
            {
                Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File {
                    Name          = System.IO.Path.GetFileName(file),
                    Description   = "",
                    AppProperties = new Dictionary <string, string> {
                        { "customKey", "customValue" }
                    },
                    MimeType = GetMimeType(file)
                };

                if (!string.IsNullOrEmpty(parentId))
                {
                    body.Parents = new List <string> {
                        parentId
                    };
                }
                else
                {
                    string folderId = CreateFolderAndGetID("DriveApiExample");
                    body.Parents = new List <string> {
                        folderId
                    };
                }

                using (var stream = new System.IO.FileStream(file, FileMode.Open, FileAccess.Read)) {
                    try {
                        FilesResource.CreateMediaUpload request = service.Files.Create(body, stream, GetMimeType(file));
                        request.SupportsTeamDrives = true;
                        request.Fields             = "id, name, createdTime, modifiedTime, mimeType, description, size";

                        request.ProgressChanged += (e) => {
                            if (e.BytesSent > 0)
                            {
                                int progress = (int)Math.Floor((decimal)((e.BytesSent * 100) / fileInfo.Length));
                                SetProgressValue(progress, "yükleniyor...");
                            }
                        };

                        request.ResponseReceived += (e) => {
                            SetProgressValue(100, "yüklendi");
                        };

                        SetProgressValue(0, "yükleniyor...");

                        await request.UploadAsync();

                        return(request.ResponseBody);
                    }
                    catch (Exception ex) {
                        throw new Exception(ex.Message);
                    }
                }
            }
            else
            {
                throw new Exception("Can not found");
            }
        }