Beispiel #1
0
        public async Task <IActionResult> OnPostUploadAsync(List <IFormFile> model)
        {
            if (!ModelState.IsValid || model == null)
            {
                return(BadRequest());
            }

            var userIdClaim = User.Claims.Single(c => c.Type == "id");
            var user        = await _userManager.FindByIdAsync(userIdClaim.Value);

            // see other considerations and solutions in the docs:
            // https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-3.1
            long size = model.Sum(f => f.Length);

            var files = new List <File>();

            foreach (var formFile in model)
            {
                if (formFile.Length > 0)
                {
                    byte[] content;
                    using (var memoryStream = new System.IO.MemoryStream())
                    {
                        await formFile.CopyToAsync(memoryStream);

                        content = memoryStream.ToArray();
                    }
                    var filename = formFile.FileName;
                    var fileId   = Guid.NewGuid();
                    files.Add(new File
                    {
                        FileId   = fileId,
                        FileBlob = content,
                        Metadata = new FileMetadata
                        {
                            FileId      = fileId,
                            ContentType = formFile.ContentType,
                            Extension   = System.IO.Path.GetExtension(filename),
                            Size        = content.LongLength,
                            Audit       = new AuditCreate
                            {
                                CreatedUserId   = user.Id,
                                CreatedUserName = user.Name
                            }
                        }
                    });
                }
            }

            files.ForEach(f =>
            {
                _fileData.Add(f);
                _imageResizer.CreateFileImageAlternates(f);
            });

            return(Ok(files.Select(x => x.Metadata)));
        }