Esempio n. 1
0
        public async Task <IActionResult> SaveFiles(int userId,
                                                    [FromForm] FileForCreationDto fileForCreationDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }


            var file         = fileForCreationDto.File;
            var uploadResult = new RawUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new RawUploadParams()
                    {
                        File = new FileDescription(file.Name, stream)
                    };
                    uploadResult = _cloudinary.Upload(uploadParams);
                };
            }
            fileForCreationDto.PublicId = uploadResult.PublicId;
            fileForCreationDto.Url      = uploadResult.Url.ToString();

            var fileToSave = _mapper.Map <File>(fileForCreationDto);
            await _repo.AddFiles(fileForCreationDto.CourseCode, fileToSave);

            if (await _repo.SaveAll())
            {
                return(Ok());
            }
            return(BadRequest("Couldn't save the file"));
        }