public async Task <IActionResult> ImportStatus(int vendorCodeId, Microsoft.AspNetCore.Http.IFormFile excelFile) { if (excelFile == null || Path.GetExtension(excelFile.FileName).ToLower() != ".xls") { AlertDanger = "You must select an .xls file."; ModelState.AddModelError("excelFile", "You must select an .xls file."); } if (ModelState.ErrorCount == 0) { var tempFile = Path.GetTempFileName(); using (var fileStream = new FileStream(tempFile, FileMode.Create)) { await excelFile.CopyToAsync(fileStream); } string file = WebUtility.UrlEncode(Path.GetFileName(tempFile)); return(RedirectToAction("ImportFile", new { id = file })); } else { return(RedirectToAction("ImportStatus")); } }
public async Task UploadPhoto(int userId, PhotoCreateDto model) { //var file = model.File; Microsoft.AspNetCore.Http.IFormFile file = model.File; var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/assets/images/", userId.ToString(), file.FileName); using (var db = base.NewDb()) { using (var stream = System.IO.File.Create(path)) { await file.CopyToAsync(stream); } bool isMain = true; if (await HasMainPhoto(userId)) { isMain = false; } var memberPhoto = new MemberPhoto() { UserId = userId, AddedDate = System.DateTime.Now, Descriptions = model.descriptions ?? file.FileName, IsMain = isMain, PhotoUrl = path }; db.Add(memberPhoto); await db.SaveChangesAsync(); return; } }
public static async Task <Guid> UploadAsObjectAsync(this Microsoft.AspNetCore.Http.IFormFile file) { Guid fileId = Guid.NewGuid(); Models.StorageAccountSettings storageAccountSettings = Common.CurrentStorageAccountSettings; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageAccountSettings.ConnectionString); CloudBlobClient client = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = client.GetContainerReference(storageAccountSettings.UploadsContainerName); CloudBlockBlob blob = null; try { string fileName = $"{fileId}.{file.FileName.Split('.').Last()}"; blob = container.GetBlockBlobReference(fileName); using (var outputStream = await blob.OpenWriteAsync()) { await file.CopyToAsync(outputStream); } } catch (Exception ex) { } return(fileId); }
public async Task <bool> UploadVideoData([FromForm] Microsoft.AspNetCore.Http.IFormFile body) { byte[] fileBytes; using (var memoryStream = new MemoryStream()) { await body.CopyToAsync(memoryStream); fileBytes = memoryStream.ToArray(); if (!Directory.Exists("./Videos")) { Directory.CreateDirectory("Videos"); } } var filename = "./Videos/" + body.FileName; var contentType = body.ContentType; bool fileWrite = ByteArrayToFile(filename, fileBytes); var user = await _userManager.FindByNameAsync("ezaz"); if (user.Videos == null) { user.Videos = new List <Video>(); } Video video = new Video(); video.Path = filename; video.UploadTime = DateTime.Now; video.Description = "in Progress"; user.Videos.Add(video); await _userManager.UpdateAsync(user); return(true); }
public async Task <IActionResult> EmailAwardStatus(int vendorCodeTypeId, Microsoft.AspNetCore.Http.IFormFile excelFile) { if (excelFile == null || !string.Equals(Path.GetExtension(excelFile.FileName), ".xls", StringComparison.OrdinalIgnoreCase)) { AlertDanger = "You must select an .xls file."; ModelState.AddModelError("excelFile", "You must select an .xls file."); return(RedirectToAction(nameof(EmailAward))); } if (ModelState.ErrorCount == 0) { var tempFile = _pathResolver.ResolvePrivateTempFilePath(); _logger.LogInformation("Accepted vendor code type {vendorCodeTypeId} email award file {UploadFile} as {TempFile}", vendorCodeTypeId, excelFile.FileName, tempFile); using (var fileStream = new FileStream(tempFile, FileMode.Create)) { await excelFile.CopyToAsync(fileStream); } string file = WebUtility.UrlEncode(Path.GetFileName(tempFile)); var site = await GetCurrentSiteAsync(); var jobToken = await _jobService.CreateJobAsync(new Job { JobType = JobType.UpdateEmailAwardStatus, SerializedParameters = JsonConvert .SerializeObject(new JobDetailsVendorCodeStatus { VendorCodeTypeId = vendorCodeTypeId, Filename = file, SiteName = site.Name }) }); return(View("Job", new ViewModel.MissionControl.Shared.JobViewModel { CancelUrl = Url.Action(nameof(EmailAward)), JobToken = jobToken.ToString(), PingSeconds = 5, SuccessRedirectUrl = "", SuccessUrl = Url.Action(nameof(EmailAward)), Title = "Loading email award status..." })); } else { return(RedirectToAction(nameof(EmailAward))); } }
private async Task <UploadStatus> uploadFile(Microsoft.AspNetCore.Http.IFormFile media, string newFileName) { string message = string.Empty; bool status = false; if (media != null) { // Create full path and save the original media file newFileName = string.IsNullOrWhiteSpace(newFileName) ? media.FileName:newFileName; var saveDir = Path.Combine("aspnetcore_files", newFileName); if (System.IO.File.Exists("aspnetcore_files/" + newFileName)) { newFileName = Guid.NewGuid().ToString() + ".png"; saveDir = Path.Combine("aspnetcore_files", newFileName); } using (var stream = new FileStream(saveDir, FileMode.Create)) { var ext = Path.GetExtension(media.FileName); var fAllows = _config.AllowFileType.Contains(ext.ToLower()); if (fAllows == false) { message = "File hanya diperbolehkan " + _config.AllowFileType; return(new UploadStatus { FileName = message, Status = status }); } if (media.Length < _config.MaxSizeUploadFile && fAllows) { await media.CopyToAsync(stream); message = newFileName; status = true; } else { message = "File maksimal berukuran " + (_config.MaxSizeUploadFile / 1048576) + "Mb"; } } } return(new UploadStatus { FileName = message, Status = status }); }
public async Task <string> UploadFileAsync(Microsoft.AspNetCore.Http.IFormFile file) { string ext = Path.GetExtension(file.FileName); string filepath = $"files/{Path.GetRandomFileName()}{ext}"; int tries = 1; while (File.Exists(filepath)) { filepath = $"files/{Path.GetRandomFileName()}_{tries}{ext}"; } using var fileStream = new FileStream(filepath, FileMode.Create); _Logger.LogInformation($"Uploading file to \"{filepath}\""); await file.CopyToAsync(fileStream); fileStream.Close(); return(filepath); }
public async Task <IActionResult> Edit(int id, Product product, Microsoft.AspNetCore.Http.IFormFile imageFile) { if (id != product.ID) { return(NotFound()); } string newFile = System.IO.Path.Combine(_env.WebRootPath, "images", imageFile.FileName); System.IO.FileInfo newFileInfo = new System.IO.FileInfo(newFile); using (System.IO.FileStream fs = newFileInfo.Create()) { await imageFile.CopyToAsync(fs); fs.Close(); } product.Image = "/images/" + imageFile.FileName; if (ModelState.IsValid) { try { _context.Update(product); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductExists(product.ID)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(product)); }
public async Task <ActionResult> Create(Hotel hotel, Microsoft.AspNetCore.Http.IFormFile photo) { if (photo != null) { string path = "/images/hotels" + DateTime.Now.ToString("ddMMyyyy") + "_" + photo.FileName; using (var fileStream = new FileStream(appEnvironment.WebRootPath + path, FileMode.Create)) { await photo.CopyToAsync(fileStream); } hotel.FotoHotel = path; } context.Hotels.Add(hotel); await context.SaveChangesAsync(); return(RedirectToAction("Index")); }
public async static Task <string> Save(Microsoft.AspNetCore.Http.IFormFile attached_file, byte type) { string date = $"_{DateTime.UtcNow.Day}_{DateTime.UtcNow.Month}_{DateTime.UtcNow.Year}_{DateTime.UtcNow.Hour}_{DateTime.UtcNow.Minute}_{DateTime.UtcNow.Second}"; string file_path = Guid.NewGuid().ToString() + date + Path.GetExtension(attached_file.FileName); string folder_path = "Assets/"; switch (type) { case 0: folder_path += "Dissertation"; break; case 1: folder_path += "Language"; break; case 2: folder_path += "Certificate"; break; case 3: folder_path += "ContactType"; break; case 4: folder_path += "ProfilePicture"; break; case 5: folder_path += "Article"; break; case 6: folder_path += "Thesis"; break; case 7: folder_path += "Textbook"; break; } var path = Path.Combine( Directory.GetCurrentDirectory(), folder_path, file_path); using (var stream = new FileStream(path, FileMode.Create)) { await attached_file.CopyToAsync(stream).ConfigureAwait(false); } return($"/{folder_path}/{file_path}"); }
public async Task <List <Department> > Import(Microsoft.AspNetCore.Http.IFormFile file) { var list = new List <Department>(); using (var stream = new MemoryStream()) { await file.CopyToAsync(stream); using (var package = new ExcelPackage(stream)) { ExcelWorksheet worksheet = package.Workbook.Worksheets[0]; var rowcount = worksheet.Dimension.Rows; for (int row = 2; row <= rowcount; row++) { list.Add(new Department { DepartmentId = worksheet.Cells[row, 1].Value.ToString().Trim(), DepartmentName = worksheet.Cells[row, 2].Value.ToString().Trim(), }); } } return(list); } }
public async Task <ActionResult> UploadExcel(Microsoft.AspNetCore.Http.IFormFile fileupload) { var dtDocumentIdList = new System.Data.DataTable(); //Checking file content length and Extension must be .xlsx if (fileupload != null) { if (fileupload.Length > 0 && fileupload.ContentType == "application/vnd.ms-excel" || fileupload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { if (!Directory.Exists(_webRootPath)) { Directory.CreateDirectory(_webRootPath); } string id = Guid.NewGuid().ToString(); string fileName = $"{Guid.NewGuid().ToString()}{ Path.GetExtension(fileupload.FileName)}"; string filePath = $"{_webRootPath}{fileName}"; using (FileStream fs = System.IO.File.Create(filePath)) { await fileupload.CopyToAsync(fs); await fs.FlushAsync(); } List <string> docIds = null; //Started reading the Excel file. using (XLWorkbook workbook = new XLWorkbook(filePath)) { IXLWorksheet worksheet = workbook.Worksheet(1); bool FirstRow = true; //Range for reading the cells based on the last cell used. string readRange = "1:1"; foreach (IXLRow row in worksheet.RowsUsed()) { //If Reading the First Row (used) then add them as column name if (FirstRow) { //Checking the Last cellused for column generation in datatable readRange = string.Format("{0}:{1}", 1, row.LastCellUsed().Address.ColumnNumber); foreach (IXLCell cell in row.Cells(readRange)) { dtDocumentIdList.Columns.Add(cell.Value.ToString()); } FirstRow = false; } else { if (docIds == null) { docIds = new List <string>(); } //Adding a Row in datatable dtDocumentIdList.Rows.Add(); int cellIndex = 0; //Updating the values of datatable foreach (IXLCell cell in row.Cells(readRange)) { docIds.Add(cell.Value.ToString()); //dt.Rows[dt.Rows.Count - 1][cellIndex] = cell.Value.ToString(); cellIndex++; } } } //If no data in Excel file if (FirstRow) { ViewBag.Message = "Empty Excel File!"; } } if (docIds == null) { return(NotFound()); } if (!Directory.Exists(_webRootDownloadPath)) { Directory.CreateDirectory(_webRootDownloadPath); } //descarga adjunto 1 var taskResult1 = await Task.WhenAll(docIds.Select(doc => DownloadFileAsync(doc, 1))); await LogActivity(_webRootDownloadPath, $"taskResult1.Lenght: {taskResult1.Length}, OK"); //descarga adjunto 2 var taskResult2 = await Task.WhenAll(taskResult1.Select(doc => DownloadFileAsync(doc, 2))); await LogActivity(_webRootDownloadPath, $"taskResult2.Lenght: {taskResult2.Length}, Error"); //lista a procesar List <string> processLst = docIds.Where(p => !taskResult2.Contains(p)).ToList(); var dtDocument = new DataTable("DB"); dtDocument.Columns.Add("DocId", typeof(string)); //add columns Constants.GetFields.ForEach(e => { dtDocument.Columns.Add(e.Name, typeof(string)); }); await Task.WhenAll(processLst.Select(s => ProcessDocument(dtDocument, s))); if (dtDocument.Rows.Count > 0) { using (XLWorkbook workbook = new XLWorkbook(filePath)) { IXLWorksheet dbSheet = workbook.AddWorksheet(dtDocument, "DB"); workbook.Save(); var bytes = await System.IO.File.ReadAllBytesAsync(filePath); const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; HttpContext.Response.ContentType = contentType; HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition"); var fileContentResult = new FileContentResult(bytes, contentType) { FileDownloadName = fileName }; TempData["Ok"] = true; return(fileContentResult); } } else { TempData["Ok"] = false; } } } else { TempData["SelectFile"] = true; } return(RedirectToAction("Index")); }