public IActionResult Upload(IList <IFormFile> files)
        {
            foreach (var file in files)
            {
                ContentDispositionHeaderValue header = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
                string fileName = header.FileName;
                fileName = fileName.Trim('"');
                fileName = Path.GetFileName(fileName);

                MemoryStream ms = new MemoryStream();
                Stream       s  = file.OpenReadStream();
                s.CopyTo(ms);
                byte[] data = ms.ToArray();
                s.Dispose();
                ms.Dispose();

                UploadedFile primaryObj = new UploadedFile();
                primaryObj.FileName    = fileName;
                primaryObj.ContentType = file.ContentType;
                primaryObj.Size        = file.Length;
                primaryObj.TimeStamp   = DateTime.Now;
                primaryObj.FileContent = data;

                IUploadedFile backupObj = primaryObj.Clone();

                //IUploadedFile backupObj = primaryObj.DeepCopy();

                //send primaryObj to main system
                //send backupObj to backup system
            }
            ViewBag.Message = files.Count + " file(s) uploaded successfully!";
            return(View("Index"));
        }
        public async Task SaveFile(IUploadedFile uploadedFile, DocumentAsset documentAsset)
        {
            using (var inputSteam = await uploadedFile.OpenReadStreamAsync())
            {
                bool isNew = documentAsset.DocumentAssetId < 1;

                documentAsset.FileExtension   = Path.GetExtension(uploadedFile.FileName).TrimStart('.');
                documentAsset.FileSizeInBytes = Convert.ToInt32(inputSteam.Length);
                documentAsset.ContentType     = uploadedFile.MimeType;

                // Save at this point if it's a new image
                if (isNew)
                {
                    await _dbContext.SaveChangesAsync();
                }

                var fileName = Path.ChangeExtension(documentAsset.DocumentAssetId.ToString(), documentAsset.FileExtension);

                using (var scope = _transactionScopeFactory.Create(_dbContext))
                {
                    // Save the raw file directly
                    await CreateFileAsync(isNew, fileName, inputSteam);

                    if (!isNew)
                    {
                        await _dbContext.SaveChangesAsync();
                    }

                    await scope.CompleteAsync();
                }
            }
        }
        /// <summary>
        /// Some shared validation to prevent image asset types from being added to documents.
        /// </summary>
        public static IEnumerable <ValidationResult> Validate(IUploadedFile file)
        {
            if (file != null && !string.IsNullOrWhiteSpace(file.FileName))
            {
                // Validate extension & mime type

                var ext = Path.GetExtension(file.FileName)?.Trim();

                if (string.IsNullOrWhiteSpace(ext))
                {
                    yield return(new ValidationResult("The file you're uploading has no file extension.", new string[] { "File" }));
                }
                else if (FilePathHelper.FileExtensionContainsInvalidChars(ext))
                {
                    yield return(new ValidationResult("The file you're uploading uses an extension containing invalid characters.", new string[] { "File" }));
                }
                else if ((ImageAssetConstants.PermittedImageTypes.ContainsKey(ext)) ||
                         (!string.IsNullOrEmpty(file.MimeType) && ImageAssetConstants.PermittedImageTypes.ContainsValue(file.MimeType)))
                {
                    yield return(new ValidationResult("Image files shoud be uploaded in the image assets section.", new string[] { "File" }));
                }

                // Validate filename

                if (string.IsNullOrWhiteSpace(file.FileName))
                {
                    yield return(new ValidationResult("The file you're uploading has no file name.", new string[] { "File" }));
                }
                else if (string.IsNullOrWhiteSpace(FilePathHelper.CleanFileName(file.FileName)))
                {
                    yield return(new ValidationResult("The file you're uploading has an invalid file name.", new string[] { "File" }));
                }
            }
        }
Exemplo n.º 4
0
 public void Loading(IUploadedFile uploadedFile)
 {
     uploadedFile.Path = @"\Files\" + uploadedFile.UploadedFile.FileName;
     using (var fileStream = new FileStream(uploadedFile.Root + uploadedFile.Path, FileMode.OpenOrCreate))
     {
         uploadedFile.UploadedFile.CopyTo(fileStream);
     }
 }
        public override void Upload(string container, string path, IUploadedFile file)
        {
            var storageAccount = new CloudStorageAccount(new StorageCredentials(ExtendedProperties["accountName"], ExtendedProperties["accessKey"]), true);
            var blobClient = storageAccount.CreateCloudBlobClient();
            var cloudContainer = blobClient.GetContainerReference(container);
            cloudContainer.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
            var blockBlob = cloudContainer.GetBlockBlobReference(path);

            blockBlob.UploadFromStream(file.Stream);
        }
        public override void Upload(string container, string path, IUploadedFile file)
        {
            client = AWSClientFactory.CreateAmazonS3Client(ExtendedProperties["accessKey"], ExtendedProperties["secretKey"], RegionEndpoint.USEast1);
            String S3_KEY = path;

            PutObjectRequest request = new PutObjectRequest();
            request.BucketName = container;
            request.Key = S3_KEY;
            request.InputStream = file.Stream;
            client.PutObject(request);
        }
        /// <summary>
        /// Some shared validation to prevent image asset types from being added to documents.
        /// </summary>
        public static IEnumerable <ValidationResult> Validate(IUploadedFile file)
        {
            if (file != null && !string.IsNullOrWhiteSpace(file.FileName))
            {
                var ext = Path.GetExtension(file.FileName);

                if ((ImageAssetConstants.PermittedImageTypes.ContainsKey(ext)) ||
                    (!string.IsNullOrEmpty(file.MimeType) && ImageAssetConstants.PermittedImageTypes.ContainsValue(file.MimeType)))
                {
                    yield return(new ValidationResult("Image files shoud be uploaded in the image assets section.", new string[] { "File" }));
                }
            }
        }
Exemplo n.º 8
0
        public async Task UpdateStudentProfile()
        {
            byte[] mockImgData = Enumerable.Range(0, 10)
                                 .Select(n => (byte)n)
                                 .ToArray();
            Mock <IUploadedFile> fileMock = new Mock <IUploadedFile>();

            fileMock
            .Setup(file => file.GetFileDataAsync())
            .ReturnsAsync(mockImgData);

            IUploadedFile mockedFile = fileMock.Object;

            _imgMock
            .Setup(imgService => imgService.SaveProfileImage(mockedFile))
            .ReturnsAsync(new ResultMessage <string>("testpath"));

            IServicesExecutor <StudentDTO, Student> executor
                = new ServiceExecutor <StudentDTO, Student>(_context, _handlerMock.Object);
            IStudentService          studentService = new StudentService(executor);
            Mock <IErrorHandler>     handlerMock    = new Mock <IErrorHandler>();
            IStudentManagmentService studMngService
                = new StudentManagmentService(
                      _emailMock.Object,
                      studentService,
                      _regMock.Object,
                      _sharedConfigMock.Object,
                      _imgMock.Object,
                      handlerMock.Object,
                      _context);

            Student stud = await _context.Students.FirstOrDefaultAsync();

            string newUsername    = "******";
            string newDescription = "New description";

            await studMngService.EditStudentProfile(stud.StudentId, new ProfileUpdateDTO
            {
                Username    = "******",
                Description = "New description",
                Photo       = fileMock.Object
            });

            stud = await _context.Students.FirstOrDefaultAsync(s => s.StudentId == stud.StudentId);

            Assert.AreEqual(newUsername, stud.Username);
            Assert.AreEqual(newDescription, stud.Description);
            _imgMock.Verify(imgService => imgService.SaveProfileImage(mockedFile), Times.Once);
        }
Exemplo n.º 9
0
      public ActionResult Upload(string title, string description, IPrincipal principal, IUploadedFile file)
      {
         if (!principal.Identity.IsAuthenticated)
            return new RedirectResult(FormsAuthentication.LoginUrl);

         if (file.ContentLength > 0)
         {
            TadImage oNewImage = TadImage.NewTadImage(file.InputStream, Guid.NewGuid() + Path.GetExtension(file.FileName));
            oNewImage.Title = title;
            oNewImage.Description = description;
            oNewImage.Save(HttpContext.User.Identity);
         }

         return RedirectToAction("Index", "Home");
      }
Exemplo n.º 10
0
      public ActionResult Upload(string title, string description, IPrincipal principal, IUploadedFile file)
      {
         if (file.ContentLength > 0)
         {
            TadmapImage image = new TadmapImage();
            image.Title = title ?? Path.GetFileNameWithoutExtension(file.FileName);
            image.Description = description ?? "";
            image.Key = Guid.NewGuid() + Path.GetExtension(file.FileName);
            image.ImageSet = new ImageSet1(image.Key);
            image.UserId = (principal.Identity as TadmapIdentity).Id;

            _imageRepository.Save(image);
         }

         return RedirectToAction("Index", "Home");
      }
Exemplo n.º 11
0
        public IUploadedFile DeepCopy()
        {
            if (!this.GetType().IsSerializable)
            {
                throw new Exception("object is not serializable");
            }

            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream    ms        = new MemoryStream();

            formatter.Serialize(ms, this);
            ms.Seek(0, SeekOrigin.Begin);
            IUploadedFile deepCopy = (IUploadedFile)formatter.Deserialize(ms);

            ms.Close();
            return(deepCopy);
        }
Exemplo n.º 12
0
        public async Task SaveFile(IUploadedFile uploadedFile, DocumentAsset documentAsset)
        {
            documentAsset.ContentType    = _mimeTypeService.MapFromFileName(uploadedFile.FileName, uploadedFile.MimeType);
            documentAsset.FileExtension  = Path.GetExtension(uploadedFile.FileName).TrimStart('.');
            documentAsset.FileNameOnDisk = "file-not-saved";

            _assetFileTypeValidator.ValidateAndThrow(documentAsset.FileExtension, documentAsset.ContentType, "File");
            ValidateFileType(documentAsset);

            var fileStamp = AssetFileStampHelper.ToFileStamp(documentAsset.FileUpdateDate);

            using (var inputSteam = await uploadedFile.OpenReadStreamAsync())
            {
                bool isNew = documentAsset.DocumentAssetId < 1;

                documentAsset.FileSizeInBytes = Convert.ToInt32(inputSteam.Length);

                using (var scope = _transactionScopeFactory.Create(_dbContext))
                {
                    // Save at this point if it's a new file
                    if (isNew)
                    {
                        await _dbContext.SaveChangesAsync();
                    }

                    // update the filename
                    documentAsset.FileNameOnDisk = $"{documentAsset.DocumentAssetId}-{fileStamp}";
                    var fileName = Path.ChangeExtension(documentAsset.FileNameOnDisk, documentAsset.FileExtension);

                    // Save the raw file directly
                    await CreateFileAsync(isNew, fileName, inputSteam);

                    // Update the filename
                    await _dbContext.SaveChangesAsync();

                    await scope.CompleteAsync();
                }
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Saves student's profile image.
        /// </summary>
        /// <param name="file">Information about file</param>
        /// <returns>Uri of the image</returns>
        public async Task <ResultMessage <string> > SaveProfileImage(IUploadedFile file)
        {
            byte[] processedImage;
            using (Stream imgStream = file.OpenReadStream())
            {
                processedImage = PreprocessImage(imgStream);
            }
            if (processedImage == null)
            {
                return(new ResultMessage <string>(OperationStatus.UnknownError));
            }
            string path = PathBuilder.BuildPathForProfileImage();
            ResultMessage <bool> result = await _docService.UploadDocumentToStorage(path, processedImage);

            if (result.IsSuccess)
            {
                return(new ResultMessage <string>(path));
            }
            else
            {
                return(new ResultMessage <string>(OperationStatus.FileSystemError));
            }
        }
        public async Task SaveAsync(
            IUploadedFile uploadedFile,
            ImageAsset imageAsset,
            string propertyName
            )
        {
            Image <Rgba32> imageFile   = null;
            IImageFormat   imageFormat = null;

            using (var inputSteam = await uploadedFile.OpenReadStreamAsync())
            {
                try
                {
                    imageFile = Image.Load(inputSteam, out imageFormat);
                }
                catch (ArgumentException ex)
                {
                    // We'll get an argument exception if the image file is invalid
                    // so lets check to see if we can identify if it is an invalid file type and show that error
                    // This might not always be the case since a file extension or mime type might not be supplied.
                    var ext = Path.GetExtension(uploadedFile.FileName);
                    if ((!string.IsNullOrEmpty(ext) && !ImageAssetConstants.PermittedImageTypes.ContainsKey(ext)) ||
                        (!string.IsNullOrEmpty(uploadedFile.MimeType) && !ImageAssetConstants.PermittedImageTypes.ContainsValue(uploadedFile.MimeType)))
                    {
                        throw ValidationErrorException.CreateWithProperties("The file is not a supported image type.", propertyName);
                    }

                    throw;
                }

                using (imageFile) // validate image file
                {
                    ValidateImage(propertyName, imageFile, imageFormat);

                    var requiredReEncoding = true;
                    var fileExtension      = "jpg";
                    var foundExtension     = _permittedImageFileExtensions
                                             .FirstOrDefault(e => imageFormat.FileExtensions.Contains(e));

                    if (foundExtension != null)
                    {
                        fileExtension      = foundExtension;
                        requiredReEncoding = false;
                    }

                    imageAsset.WidthInPixels   = imageFile.Width;
                    imageAsset.HeightInPixels  = imageFile.Height;
                    imageAsset.FileExtension   = fileExtension;
                    imageAsset.FileSizeInBytes = inputSteam.Length;

                    using (var scope = _transactionScopeManager.Create(_dbContext))
                    {
                        var fileName = Path.ChangeExtension(imageAsset.FileNameOnDisk, imageAsset.FileExtension);

                        if (requiredReEncoding)
                        {
                            // Convert the image to jpg
                            using (var outputStream = new MemoryStream())
                            {
                                if (requiredReEncoding)
                                {
                                    imageFile.Save(outputStream, new JpegEncoder());
                                }
                                else
                                {
                                    imageFile.Save(outputStream, imageFormat);
                                }

                                await _fileStoreService.CreateAsync(ASSET_FILE_CONTAINER_NAME, fileName, outputStream);

                                // recalculate size and save
                                imageAsset.FileSizeInBytes = outputStream.Length;
                            }
                        }
                        else
                        {
                            // Save the raw file directly
                            await _fileStoreService.CreateAsync(ASSET_FILE_CONTAINER_NAME, fileName, inputSteam);
                        }

                        await _dbContext.SaveChangesAsync();

                        await scope.CompleteAsync();
                    };
                }
            }
        }
Exemplo n.º 15
0
 public abstract void Upload(string containerName, string fileName, IUploadedFile file);
Exemplo n.º 16
0
 public Task SaveAsync(IUploadedFile uploadedFile, ImageAsset imageAsset, string propertyName)
 {
     throw new ImageAssetFileServiceNotImplementedException();
 }
Exemplo n.º 17
0
 public Task SaveAsync(IUploadedFile uploadedFile, ImageAsset imageAsset, string propertyName)
 {
     throw new NotImplementedException("No image file plugin installed. To use image assets you need to reference an image asset plugin.");
 }
Exemplo n.º 18
0
        public async Task SaveFile(IUploadedFile uploadedFile, ImageAsset imageAsset)
        {
            Image imageFile = null;

            using (var inputSteam = await uploadedFile.GetFileStreamAsync())
            {
                try
                {
                    imageFile = Image.FromStream(inputSteam);
                }
                catch (ArgumentException ex)
                {
                    // We'll get an argument exception if the image file is invalid
                    // so lets check to see if we can identify if it is an invalid file type and show that error
                    // This might not always be the case since a file extension or mime type might not be supplied.
                    var ext = Path.GetExtension(uploadedFile.FileName);
                    if ((!string.IsNullOrEmpty(ext) && !ImageAssetConstants.PermittedImageTypes.ContainsKey(ext)) ||
                        (!string.IsNullOrEmpty(uploadedFile.MimeType) && !ImageAssetConstants.PermittedImageTypes.ContainsValue(uploadedFile.MimeType)))
                    {
                        throw new PropertyValidationException("The file is not a supported image type.", "File");
                    }

                    throw;
                }

                using (imageFile) // validate image file
                {
                    bool requiredReEncoding = !_permittedImageFileExtensionMap.ContainsKey(imageFile.RawFormat);
                    bool isNew = imageAsset.ImageAssetId < 1;

                    var imageFormat = requiredReEncoding ? ImageFormat.Jpeg : imageFile.RawFormat;

                    imageAsset.Width     = imageFile.Width;
                    imageAsset.Height    = imageFile.Height;
                    imageAsset.Extension = _permittedImageFileExtensionMap[imageFormat].First().TrimStart('.');
                    imageAsset.FileSize  = Convert.ToInt32(inputSteam.Length);

                    // Save at this point if it's a new image
                    if (isNew)
                    {
                        await _dbContext.SaveChangesAsync();
                    }

                    using (var scope = _transactionScopeFactory.Create())
                    {
                        var fileName = Path.ChangeExtension(imageAsset.ImageAssetId.ToString(), imageAsset.Extension);

                        if (requiredReEncoding)
                        {
                            // Convert the image to jpg
                            using (var outputStream = new MemoryStream())
                            {
                                imageFile.Save(outputStream, imageFormat);
                                CreateFile(isNew, fileName, outputStream);
                                // recalculate size and save
                                imageAsset.FileSize = Convert.ToInt32(outputStream.Length);
                                await _dbContext.SaveChangesAsync();
                            }
                        }
                        else
                        {
                            // Save the raw file directly
                            CreateFile(isNew, fileName, inputSteam);
                        }

                        scope.Complete();
                    };
                }
            }
        }