public static T ToObject <T>(this FormPostResult result, string dataFieldName) where T : new() { var fieldValue = result?.Fields?.GetValues(dataFieldName)?.FirstOrDefault(); if (string.IsNullOrWhiteSpace(fieldValue)) { return(default(T)); } var serializer = new JsonSerializer(); var data = serializer.Deserialize <T>(fieldValue); return(data); }
public static async Task <FormPostResult> ProcessFormPostAsync(this ApiController controller, string destinationFolder, Func <string, string> getDestinationFileName = null, Func <string, string> getEnforcedFileNameExtension = null, IImageProcessor imageProcessor = null) { if (Directory.Exists(destinationFolder)) { var filesToBeDeleted = Directory.GetFiles(destinationFolder, "BodyPart_*"); foreach (var fileToBeDeleted in filesToBeDeleted) { File.Delete(fileToBeDeleted); } } else { Directory.CreateDirectory(destinationFolder); } var request = controller.Request; if (!request.Content.IsMimeMultipartContent()) { return(new FormPostResult() .WithProcessResult(ProcessResultType.UnsupportedMediaType, "Media type is not supported")); } var provider = new MultipartFormDataStreamProvider(destinationFolder); await request.Content.ReadAsMultipartAsync(provider); var result = new FormPostResult { Files = provider.FileData .Select(x => new UploadFileInfoDto { MediaType = x.Headers.ContentType.MediaType, FileName = x.Headers.ContentDisposition.FileName.Replace("\"", string.Empty), TempFileName = x.LocalFileName }).ToList(), Fields = provider.FormData }; var exceptions = new List <Exception>(); foreach (var uploadFileInfo in result.Files) { try { var tempFile = Path.Combine(destinationFolder, uploadFileInfo.TempFileName); var processedFile = tempFile; if (imageProcessor != null) { processedFile = Path.Combine(destinationFolder, Guid.NewGuid().ToString()); imageProcessor.Process(tempFile, processedFile); } var fileName = getDestinationFileName?.Invoke(uploadFileInfo.FileName) ?? uploadFileInfo.FileName; if (getEnforcedFileNameExtension == null) { uploadFileInfo.FullFilePath = Path.Combine(destinationFolder, fileName); } else { uploadFileInfo.FullFilePath = Path.Combine(destinationFolder, Path.GetFileNameWithoutExtension(fileName) + '.' + getEnforcedFileNameExtension(fileName).TrimStart('.')); } if (File.Exists(uploadFileInfo.FullFilePath)) { File.Delete(uploadFileInfo.FullFilePath); } File.Move(processedFile, uploadFileInfo.FullFilePath); File.Delete(processedFile); } catch (Exception ex) { exceptions.Add(ex); } } result = exceptions.Any() ? result.WithProcessResult(exceptions) : result.WithProcessResult(ProcessResultType.Ok); return(result); }