コード例 #1
0
        public async Task <IActionResult> OnPostUploadMeetingMinuteAsync(CancellationToken cancellationToken, [FromForm] RequiredFileDto FileUploaded)
        {
            if (!ModelState.IsValid)
            {
                //need to manually add this due to a bug in the model binding process for .net core
                //see issue here https://github.com/JeremySkinner/FluentValidation/issues/1029
                ModelState.AddModelError("FileUploaded.FileToUpload",
                                         ModelState.Keys.Where(k => k == "FileToUpload").Select(k => ModelState[k].Errors[0].ErrorMessage).First());

                //set the pagemodel property to be the values submitted by the user
                //not doing this will cause all model state errors to be lost
                this.FileUploaded = FileUploaded;
                return(Partial("_UploadMeetingMinutePartial", this));
            }

            var baseAPIUrl = $"api/boardmeetings/{Id}";

            try
            {
                //call the api with a GET request
                //ensure to set the httpcompletion mode to response headers read
                //this allows the response to be read as soon as content starts arriving instead of having to wait
                //until the entire response is read
                //with this option, we can read the response content into a stream and deserialize it
                var response = await(await _apiClient.WithAuthorization()).GetAsync(baseAPIUrl,
                                                                                    HttpCompletionOption.ResponseHeadersRead, cancellationToken);

                //return the same page with an error message if the user is trying to call the API too many times
                if (response.StatusCode == HttpStatusCode.TooManyRequests)
                {
                    TempData["TooManyRequests"] = "Too many requests. Please slow down with your requests";
                    return(Partial("_UploadMeetingMinutePartial", this));
                }

                //ensure success status code else throw an exception
                response.EnsureSuccessStatusCode();

                //read the response content into a stream
                var streamContent = await response.Content.ReadAsStreamAsync();

                //deserialize the stream into an object (see StreamExtensions on how this is done)
                boardMeeting = streamContent.ReadAndDeserializeFromJson <BoardMeetingViewDto>();
            }
            catch (HttpRequestException ex)
            {
                _logger.LogError($"An error occured accessing the API. Url: {HttpContext.Request.GetDisplayUrl()}" +
                                 $" Error Message: {ex.Message}");

                //either the API is not running or an error occured on the server
                TempData["Error"] = "An error occured while processing your request. Please try again later.";
                return(Partial("_UploadMeetingMinutePartial", this));
            }

            //GetFileTypeExtension returns a tuple that is deconstructed into separate variables
            var(FileType, FileExtension) = _fileValidate.GetFileTypeExtension(FileUploaded.FileToUpload);

            try
            {
                //if meeting minute id is null, it does not exist so do a post request
                if (boardMeeting.MeetingMinuteId == null)
                {
                    baseAPIUrl = $"api/boardmeetings/{Id}/meetingminutes";

                    //generate the file name instead of letting the user provide one
                    FileName = $"MeetingMinute_{DateTime.Now.ToString("MM-dd-yyyy_HH-mm-ss")}{FileExtension}";

                    //set the MeetingMinute filename here as otherwise it will be null
                    //this property is generated by the server and not provided by the user
                    var meetingToCreate = new MeetingMinuteInputDto {
                        FileName = this.FileName
                    };

                    //get the response with authorization as the API endpoint requires an authenticated user
                    var response = await(await _apiClient.WithAuthorization()).PostAsJsonAsync <MeetingMinuteInputDto>(baseAPIUrl,
                                                                                                                       meetingToCreate, cancellationToken);

                    //return the same page with an error message if the user is trying to call the API too many times
                    if (response.StatusCode == HttpStatusCode.TooManyRequests)
                    {
                        TempData["TooManyRequests"] = "Too many requests. Please slow down with your requests";
                        return(Partial("_UploadMeetingMinutePartial", this));
                    }

                    //ensure success status code else throw an exception
                    response.EnsureSuccessStatusCode();
                }
                else
                {
                    //meeting minute already exists so just need to upload the new file
                    //no need to update anything as we will re-use the existing file name
                    FileName = boardMeeting.FileName;
                }
            }
            catch (HttpRequestException ex)
            {
                _logger.LogError($"An error occured accessing the API. Url: {HttpContext.Request.GetDisplayUrl()}" +
                                 $" Error Message: {ex.Message}");

                //either the API is not running or an error occured on the server
                TempData["Error"] = "An error occured while processing your request. Please try again later.";
                return(Partial("_UploadMeetingMinutePartial", this));
            }


            //MeetingMinute was created/updated successfully so can upload file to blob storage
            var blobFileToUpload = _azureBlob.GetAzureBlobFileReference(FileName, AzureBlobFolder);

            //set the content type of the blob file so that downloads suggest correct file type to save as
            blobFileToUpload.Properties.ContentType = FileType;

            //upload the file to Azure
            await _azureBlob.UploadAzureBlobFileAsync(FileUploaded.FileToUpload, blobFileToUpload);

            //if successful, return the partial view which will have the IsValid value set to true by default
            //this is because ajax is used to post the form rather than a submit button
            return(Partial("_UploadMeetingMinutePartial", this));
        }
コード例 #2
0
ファイル: Events.cshtml.cs プロジェクト: vrao1020/netcorehoa
        private async Task UploadImagesAsync(string fileType)
        {
            //create a stream so that the image can be read to be resized
            using (var memoryStream = new MemoryStream())
            {
                //read the file into the stream
                await ImageUploaded.FileToUpload.CopyToAsync(memoryStream);

                //set the position to 0 so that the file is not empty
                memoryStream.Position = 0;

                //create another temp stream that will be used to hold the resized image
                using (var outStream = new MemoryStream())
                {
                    //resize the image uploaded into the correct size
                    MagicImageProcessor.ProcessImage(memoryStream, outStream,
                                                     new ProcessImageSettings
                    {
                        Width      = 400,
                        Height     = 400,
                        ResizeMode = CropScaleMode.Crop,
                        HybridMode = HybridScaleMode.FavorSpeed
                    });

                    //set the position to 0 so that the file is not empty
                    outStream.Position = 0;

                    //get a reference to the file in Azure
                    var blobFileToUpload = _azureBlob.GetAzureBlobFileReference(ImageName, AzureBlobFolder);

                    //set the content type of the blob file so that downloads suggest correct file type to save as
                    blobFileToUpload.Properties.ContentType = fileType;

                    //upload the original resized image
                    await _azureBlob.UploadAzureBlobFileAsync(outStream, blobFileToUpload);
                }

                //create another temp stream that will be used to hold the thumbnail image
                using (var outStream = new MemoryStream())
                {
                    //set the position to 0 so that the file is not empty
                    memoryStream.Position = 0;

                    //resize the image uploaded into the correct size
                    MagicImageProcessor.ProcessImage(memoryStream, outStream,
                                                     new ProcessImageSettings
                    {
                        Width      = 200,
                        Height     = 200,
                        ResizeMode = CropScaleMode.Crop,
                        HybridMode = HybridScaleMode.FavorSpeed
                    });

                    //set the position to 0 so that the file is not empty
                    outStream.Position = 0;

                    //get a reference to the file in Azure
                    var blobFileToUpload = _azureBlob.GetAzureBlobFileReference(ThumbnailName, AzureBlobFolder);

                    //set the content type of the blob file so that downloads suggest correct file type to save as
                    blobFileToUpload.Properties.ContentType = fileType;

                    //upload the original resized image
                    await _azureBlob.UploadAzureBlobFileAsync(outStream, blobFileToUpload);
                }
            }
        }