Example #1
0
        //Using FileUploadFormModal, store file selected by user
        //and generate attachment url. Upload to S3 and save necessary
        //information to Attachment table
        public async Task <IActionResult> FileUploadForm(FileUploadFormModal FileUpload, string attachmentCategory, string attachmentDescription, int byufegId)
        {
            //Copy file into memory stream to obtain length
            using (var memoryStream = new MemoryStream())
            {
                await FileUpload.FormFile.CopyToAsync(memoryStream);

                // Upload the file if less than 15 MB
                if (memoryStream.Length < 15097152)
                {
                    //Call UploadImage method from S3File class to upload to S3
                    await S3File.UploadImage(FileUpload.FormFile);

                    //Load pertinent data to Attachment table
                    var name = FileUpload.FormFile.FileName.Replace(" ", "");
                    context.Attachment.Add(new Attachment()
                    {
                        ByufegId      = byufegId,
                        Description   = attachmentDescription,
                        Category      = attachmentCategory,
                        AttachmentUrl = $"https://elasticbeanstalk-us-east-1-453718841465.s3.amazonaws.com/{name}"
                    });

                    context.SaveChanges();
                }
                else
                {
                    ModelState.AddModelError("File", "The file is too large.");
                }
            }

            return(RedirectToAction("Data"));
        }
Example #2
0
        public async Task <IResult <S3File> > GetS3FileAsync(S3Key key)
        {
            try
            {
                using var response = await _s3Client.GetObjectAsync(BucketName, key.Value);

                await using var responseStream = response.ResponseStream;
                using var reader = new StreamReader(responseStream);

                var responseBody = await reader.ReadToEndAsync();

                var result = new S3File(responseBody);

                return(Result.Success(result));
            }
            catch (AmazonS3Exception)
            {
                return(Result.Failure <S3File>($"Specified key does not exist: {key.Value}"));
            }
            catch (Exception e)
            {
                var error = $"Error encountered. Message:'{e.Message}' when reading object";
                return(Result.Failure <S3File>(error));
            }
        }
Example #3
0
        public void DeleteFromS3(S3File file)
        {
            if (file is null || file.RemoteFilePath is null || file.Bucket is null || file.LocalFilePath is null)
            {
                throw new Exception("S3 File is NULL or has some NULL attributes");
            }

            if (Credentials is null || Credentials.AWS_AccessKey is null || Credentials.AWS_SecretKey is null || Credentials.Region is null)
            {
                throw new CredentialsNotProvidedException();
            }

            try
            {
                using (AmazonS3Client client = getS3Client(Credentials))
                {
                    DeleteObjectRequest request = new
                                                  DeleteObjectRequest();

                    request.BucketName = file.Bucket;
                    request.Key        = file.RemoteFilePath;

                    Task <DeleteObjectResponse> task = client.DeleteObjectAsync(request);
                    task.Wait();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #4
0
        public void DownloadFromS3(S3File file)
        {
            if (file is null || file.RemoteFilePath is null || file.Bucket is null || file.LocalFilePath is null)
            {
                throw new Exception("S3 File is NULL or has some NULL attributes");
            }

            if (Credentials is null || Credentials.AWS_AccessKey is null || Credentials.AWS_SecretKey is null || Credentials.Region is null)
            {
                throw new CredentialsNotProvidedException();
            }

            try
            {
                TransferUtility fileTransferUtility = new
                                                      TransferUtility(getS3Client(Credentials));

                TransferUtilityDownloadRequest fileTransferUtilityRequest = new TransferUtilityDownloadRequest
                {
                    BucketName = file.Bucket,
                    FilePath   = file.LocalFilePath,
                    Key        = file.RemoteFilePath,
                };
                fileTransferUtility.Download(fileTransferUtilityRequest);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #5
0
        public void DownloadFromS3(S3File file, AmazonS3Client client)
        {
            if (file is null || file.RemoteFilePath is null || file.Bucket is null || file.LocalFilePath is null)
            {
                throw new Exception("S3 File is NULL or has some NULL attributes");
            }

            try
            {
                TransferUtility fileTransferUtility = new
                                                      TransferUtility(client);

                TransferUtilityDownloadRequest fileTransferUtilityRequest = new TransferUtilityDownloadRequest
                {
                    BucketName = file.Bucket,
                    FilePath   = file.LocalFilePath,
                    Key        = file.RemoteFilePath,
                };
                fileTransferUtility.Download(fileTransferUtilityRequest);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #6
0
        public void UploadUserAvatar_Stream_Test()
        {
            string path   = @"C:\Users\andreea.botoc\Dropbox\Camera Uploads\pic1.jpg";
            var    userid = Guid.NewGuid().ToString();

            using (var fs = new FileStream(path, FileMode.Open))
            {
                userid = Guid.NewGuid().ToString();
                S3File f        = S3.UploadUserAvatar(userid, "pic1.jpg", fs);
                var    req      = WebRequest.Create(f.Url);
                var    response = req.GetResponse();
                Assert.IsTrue(response.ContentLength > 0);
            }
        }
Example #7
0
        public async Task <(bool, HttpStatusCode, string)> DeleteS3FileAsync(S3File file, CancellationToken cancellationToken = default)
        {
            var normalizedBucket = HttpUtility.UrlEncode(file.Bucket);
            var normalizedKey    = HttpUtility.UrlEncode(file.Key);
            var normalizedFile   = HttpUtility.UrlEncode(file.File);
            var uri = new Uri(_commonApiBaseUri, $"api/files/{normalizedBucket}/{normalizedKey}/{normalizedFile}");

            using var responseMessage = await _httpClient.DeleteAsync(uri, cancellationToken);

            if (responseMessage.StatusCode == HttpStatusCode.NoContent)
            {
                return(true, HttpStatusCode.NoContent, string.Empty);
            }

            return(false, responseMessage.StatusCode, await responseMessage.Content.ReadAsStringAsync());
        }
Example #8
0
        public ActionResult UploadAvatar(UserProfileViewModel model)
        {
            if (model.ImageUpload != null && model.ImageUpload.ContentLength > 0 && model.ImageUpload.ContentLength < 1024 * 1024)
            {
                var profile = db.UserProfiles.First(p => p.UserName == User.Identity.Name);

                var customExisting = db.Avatars.FirstOrDefault(p => p.CustomForUserId == profile.UserId);
                if (customExisting != null)
                {
                    if (!String.IsNullOrEmpty(customExisting.Key))
                    {
                        S3.DeleteFile(customExisting.Key);
                    }

                    S3File f = S3.UploadUserAvatar(
                        profile.UserId.ToString(),
                        model.ImageUpload.FileName,
                        model.ImageUpload.InputStream);

                    customExisting.Url = f.Url;
                    customExisting.Key = f.Key;
                    profile.Avatar     = customExisting;
                }
                else
                {
                    var f = S3.UploadUserAvatar(
                        profile.UserId.ToString(),
                        model.ImageUpload.FileName,
                        model.ImageUpload.InputStream);

                    Avatar custom = new Avatar()
                    {
                        CustomForUserId = profile.UserId,
                        Url             = f.Url,
                        Key             = f.Url
                    };
                    db.Avatars.Add(custom);
                    profile.Avatar = custom;
                }

                db.SaveChanges();

                ((UserProfile)Session["UserInfo"]).Avatar = profile.Avatar;
            }

            return(RedirectToAction("Index"));
        }
Example #9
0
        public async Task <IResult> PutS3FileAsync(S3File obj, S3Key s3Key)
        {
            try
            {
                var putRequest = new PutObjectRequest
                {
                    BucketName  = BucketName,
                    Key         = s3Key.Value,
                    ContentBody = obj.Content
                };

                await _s3Client.PutObjectAsync(putRequest);

                return(Result.Success());
            }
            catch (Exception e)
            {
                var error = $"Error encountered. Message:'{e.Message}' when writing object";
                return(Result.Failure(error));
            }
        }
Example #10
0
        public ActionResult UploadBookPicture(BookImageUploadViewModel model)
        {
            try
            {
                if (model.ImageUpload != null &&
                    model.ImageUpload.ContentLength > 0 &&
                    model.ImageUpload.ContentLength < 1024 * 1024 &&
                    model.UploadForBookId != 0)
                {
                    S3File f = S3.UploadBookImage(
                        model.UploadForBookId.ToString(),
                        model.ImageUpload.FileName,
                        model.ImageUpload.InputStream);

                    using (var db = new SDCContext())
                    {
                        var book = db.Books.Include(b => b.Pictures).First(b => b.Id == model.UploadForBookId);
                        book.Pictures.Add(new BookPicture()
                        {
                            Url    = f.Url,
                            Key    = f.Key,
                            Title  = "",
                            IsMain = false
                        });

                        db.SaveChanges();
                        return(new HttpStatusCodeResult(HttpStatusCode.OK));
                    }
                }
                else
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #11
0
        public void DeleteFromS3(S3File file, AmazonS3Client client)
        {
            if (file is null || file.RemoteFilePath is null || file.Bucket is null || file.LocalFilePath is null)
            {
                throw new Exception("S3 File is NULL or has some NULL attributes");
            }

            try
            {
                DeleteObjectRequest request = new
                                              DeleteObjectRequest();

                request.BucketName = file.Bucket;
                request.Key        = file.RemoteFilePath;

                Task <DeleteObjectResponse> task = client.DeleteObjectAsync(request);
                task.Wait();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }