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 async Task Upload(Stream stream, Google.Apis.Drive.v2.Data.File file) { try { FilesResource.InsertMediaUpload request = service.Files.Insert(file, stream, file.MimeType); request.ProgressChanged += Upload_ProgressChanged; request.ResponseReceived += Upload_ResponseReceived; var progress = await request.UploadAsync(); //sem = new Semaphore(0, 1, "GDrive_FileUpload"); //await Task.FromResult(sem.WaitOne()); } catch (Exception e) { #if DEBUG System.Diagnostics.Debug.WriteLine("An error occurred: " + e.Message); #endif } }
public async Task <ActionResult> IndexAsync(CancellationToken cancellationToken) { //var test = model.SelectedSubject; var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()). AuthorizeAsync(cancellationToken); if (result.Credential != null) { var service = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = result.Credential, ApplicationName = "ASP.NET MVC Sample" }); Google.Apis.Drive.v2.Data.File file = new Google.Apis.Drive.v2.Data.File(); file.Title = "anushan78"; file.Description = "test"; file.MimeType = "application/pdf"; byte[] byteArray = System.IO.File.ReadAllBytes(@"F:\Files\Documents\Tickets\Confirmation _ Village Cinemas.pdf"); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.InsertMediaUpload request = service.Files.Insert(file, stream, "applicaion/pdf"); var awList = await request.UploadAsync(); } catch (Exception ex) { return(View()); } var list = await service.Files.List().ExecuteAsync(); //var tempFile = await service.Files.Get("").ExecuteAsync(); ViewBag.Message = "FILE COUNT IS: " + list.Items.Count(); return(View("Index")); } else { return(new RedirectResult(result.RedirectUri)); } }
public async Task <string> UploadImageToCloud(byte[] byteArrayContent, string fileName, string fileExstension, string parentPath = WebStorageConstants.Collection) { // var parentId = await this.CreateDirectory(parentPath); Permission permission = new Permission() { Role = "reader", Type = "anyone", WithLink = true }; File body = new File { Title = fileName, Shared = true, Permissions = new List <Permission>() { permission } }; 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); } }
public async Task <ActionResult> UploadGoogleFileAsync(HttpPostedFileBase file, Document document, CancellationToken cancellationToken) { var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()). AuthorizeAsync(cancellationToken); if (result.Credential != null) { var service = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = result.Credential, ApplicationName = "WorkCard.vn" }); if (file != null) { if (file.ContentLength > 0) { var fileName = System.IO.Path.GetFileName(file.FileName); var path = System.IO.Path.Combine(Server.MapPath("~/App_Data/Uploads/GoogleDrives"), fileName); file.SaveAs(path); File _file = new File(); _file.Title = file.FileName; _file.Description = "From WorkCard.vn; "; _file.MimeType = GetMimeType(file.FileName); _file.CanComment = true; _file.Shared = true; _file.Shareable = true; using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open)) { try { FilesResource.InsertMediaUpload request = service.Files.Insert(_file, stream, _file.MimeType); await request.UploadAsync(); if (request.ResponseBody != null) { using (ApplicationDbContext context = new ApplicationDbContext()) { document.Id = Guid.NewGuid(); document.Load(request.ResponseBody); document.CreatedBy = User.Identity.Name; document.CreatedDate = DateTime.Now; context.Documents.Add(document); await context.SaveChangesAsync(); } } } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } } } if (Request.IsAjaxRequest()) { return(PartialView()); } } return(RedirectToAction("Details", "Articles", new { id = document.ArticleId })); } else { return(new RedirectResult(result.RedirectUri)); } }
protected override void Start() { try { if (Status != StatusType.Queued) { throw new Exception("Stream has not been queued."); } base.Start(); List <File> children = null; File parent = API.DriveService._GetCachedFile(_parentId, true, false, ref children); string fileName = System.IO.Path.GetFileNameWithoutExtension(_originalTitle); string fileExtenstion = System.IO.Path.GetExtension(_originalTitle); string title = fileName; if (!String.IsNullOrEmpty(fileExtenstion)) { title += fileExtenstion; } int index = 0; while (true) { bool found = false; foreach (File child in children) { if (child.Title == title) { FileInfoType fileInfoType = API.DriveService.GetFileInfoType(child); if (IsFolder && fileInfoType == FileInfoType.Folder) { found = true; } else if (!IsFolder && fileInfoType != FileInfoType.Folder) { found = true; } } } if (!found) { break; } index++; title = fileName + " (" + index + ")"; if (!String.IsNullOrEmpty(fileExtenstion)) { title += fileExtenstion; } } _title = title; var file = new File(); var parentReference = new ParentReference { Id = _parentId }; file.Parents = new List <ParentReference> { parentReference }; file.Title = _title; file.Description = "Created by Drive Fusion Shell Extention"; file.FileExtension = System.IO.Path.GetExtension(_title); file.MimeType = _mimeType; file.ModifiedDate = _lastWriteTime.ToUniversalTime(); _FileInfo = API.DriveService.GetFileInfo(file); if (_FileInfo.IsFolder) { Lock(); using (API.DriveService.Connection connection = API.DriveService.Connection.Create()) { FilesResource.InsertRequest request = connection.Service.Files.Insert(file); request.Fields = API.DriveService.RequestFields.FileFields; file = request.Execute(); _FileId = file.Id; _FileInfo = API.DriveService.GetFileInfo(file); DriveService_ProgressChanged(UploadStatus.Completed, 0, null); } } else { Lock(_filePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); using (API.DriveService.Connection connection = API.DriveService.Connection.Create()) { FilesResource.InsertMediaUpload request = connection.Service.Files.Insert(file, _FileStream, _mimeType); request.Fields = API.DriveService.RequestFields.FileFields; request.ProgressChanged += DriveService_ProgressChanged; request.ResponseReceived += DriveService_ResponseReceived; request.ChunkSize = FilesResource.InsertMediaUpload.DefaultChunkSize; request.Pinned = _parameters.Pinned; request.UseContentAsIndexableText = _parameters.UseContentAsIndexableText; _CancellationTokenSource = new System.Threading.CancellationTokenSource(); System.Threading.Tasks.Task <IUploadProgress> task = request.UploadAsync(_CancellationTokenSource.Token); } } } catch (Exception exception) { try { _Status = StatusType.Failed; _ExceptionMessage = exception.Message; DriveService_ProgressChanged(UploadStatus.Failed, 0, exception); } catch { Debugger.Break(); } Log.Error(exception); } }