public async Task <JsonResult> FileUpload(int documentId) { var results = new List <FileUploadAttachmentResult>(); List <Attachment> attachmentsTempData = null; if (TempData[PortalHelpers.TempDataKeys.Attachments] != null) { attachmentsTempData = (List <Attachment>)TempData[PortalHelpers.TempDataKeys.Attachments]; } attachmentsTempData = attachmentsTempData ?? new List <Attachment>(); foreach (string file in Request.Files) { var fileContent = Request.Files[file]; if (fileContent != null && fileContent.ContentLength > 0) { var path = PortalHelpers.GetStorageFolderPath($"Temp/{Guid.NewGuid()}.dat"); var attachment = new FileUploadAttachmentResult { AttachmentsId = Stuff.Random.Next(int.MaxValue), FileName = fileContent.FileName, FilePath = path, CreatedByUserId = CurrentUserId, DocumentId = documentId, FileSize = fileContent.ContentLength, ContentType = fileContent.ContentType ?? System.Net.Mime.MediaTypeNames.Application.Octet }; attachment.Whitelisted = PortalHelpers.VerifyFileAccept( Properties.Settings.Default.AttachmentFileUploadAccept, attachment.FileName, attachment.ContentType); if (attachment.Whitelisted) { try { using (var fileStream = System.IO.File.Create(path)) { await fileContent.InputStream.CopyToAsync(fileStream); } attachment.Added = true; } catch (Exception ex) { attachment.SaveError = true; attachment.ErrorMessages.Add(ex.Message); } } else { attachment.ErrorMessages.Add(Properties.Settings.Default.AttachmentFileUploadAcceptMessage); } results.Add(attachment); } } attachmentsTempData.AddRange(results.Where(z => z.Added)); TempData[PortalHelpers.TempDataKeys.Attachments] = attachmentsTempData; return(Json(results)); }
public async Task <IActionResult> FileUpload(int documentId) { var results = new List <FileUploadAttachmentResult>(); var attachmentsTempData = TempData.FileUploadAttachmentResults(); foreach (var file in Request.Form.Files) { if (file.Length > 0) { var fn = $"{Guid.NewGuid()}.dat"; var attachment = new FileUploadAttachmentResult { AttachmentsId = Stuff.Random.Next(int.MaxValue), FileName = file.FileName, CreatedByUserId = CurrentUserId, DocumentId = documentId, FileSize = file.Length, ContentType = file.ContentType ?? System.Net.Mime.MediaTypeNames.Application.Octet }; attachment.Whitelisted = PortalHelpers.VerifyFileAccept(attachment.FileName, attachment.ContentType); if (attachment.Whitelisted) { attachment.FilePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName()); try { using (var fileStream = System.IO.File.Create(attachment.FilePath)) { await file.CopyToAsync(fileStream); } attachment.Added = true; attachmentsTempData.Add(attachment); } catch (Exception ex) { attachment.SaveError = true; attachment.ErrorMessages.Add(ex.Message); } } else { attachment.ErrorMessages.Add(PortalHelpers.AttachmentFileUploadAcceptMessage); } results.Add(attachment); } } TempData.FileUploadAttachmentResults(attachmentsTempData); return(Json(results)); }