Esempio n. 1
0
        public async Task <ResponseModel <FileContentResultModel> > Handle(GetByFileNameQuery request, CancellationToken cancellationToken)
        {
            var fileExtension     = Path.GetExtension(request.FileName);
            var categoryPath      = Path.Combine(_contentRootPath, "Archive", request.CategoryName);
            var fileAbsolutePath  = Path.Combine(categoryPath, request.FileName);
            var fileContentResult = new FileContentResultModel();

            if (fileExtension != FileConstants.AesExtension && fileExtension != FileConstants.RijndaelExtension)
            {
                if (!Directory.Exists(categoryPath))
                {
                    return(ResponseProvider.NotFound <FileContentResultModel>(nameof(request.CategoryName)));
                }
                if (!File.Exists(fileAbsolutePath))
                {
                    return(ResponseProvider.NotFound <FileContentResultModel>(nameof(request.FileName)));
                }

                fileContentResult.StreamData = await FileHelpers.ReadFileToMemoryStream(fileAbsolutePath);

                fileContentResult.FileName = request.FileName;
            }

            using (FileStream fs = File.Open(fileAbsolutePath, FileMode.Open))
            {
                byte[] data = new BinaryReader(fs).ReadBytes((int)fs.Length);

                fileContentResult.StreamData = await DecryptFile(data, fileExtension);

                fileContentResult.FileName = Path.GetFileNameWithoutExtension(request.FileName);

                return(ResponseProvider.Ok(fileContentResult));
            }
        }
Esempio n. 2
0
        public async Task <ResponseModel <PagedList <EncryptedFile> > > Handle(FullListQuery request, CancellationToken cancellationToken)
        {
            var encryptedFiles = _context.EncryptedFiles
                                 .AsNoTracking();

            var response = await PagedList <EncryptedFile> .Create(encryptedFiles, request.Page, request.PageSize);

            return(ResponseProvider.Ok(response));
        }
        public async Task <ResponseModel> Handle(MultipleFileUploadCommand request, CancellationToken cancellationToken)
        {
            var errorModel = new FormFileErrorModel();

            if (!MultipartRequestHelper.IsMultipartContentType(_accessor.HttpContext.Request.ContentType))
            {
                errorModel.Errors.Add("File",
                                      $"The request couldn't be processed (Error 1).");

                return(ResponseProvider.Ok(errorModel));
            }
            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(_accessor.HttpContext.Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader  = new MultipartReader(boundary, _accessor.HttpContext.Request.Body);
            var section = await reader.ReadNextSectionAsync(cancellationToken);

            while (section != null)
            {
                var hasContentDispositionHeader =
                    ContentDispositionHeaderValue.TryParse(
                        section.ContentDisposition, out var contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (!MultipartRequestHelper
                        .HasFileContentDisposition(contentDisposition))
                    {
                        errorModel.Errors.Add("File", $"The request couldn't be processed (Error 2).");

                        return(ResponseProvider.Ok(errorModel));
                    }
                    else
                    {
                        var streamedFileContent = await FileHelpers.ProcessStreamedFile(
                            section, contentDisposition, errorModel,
                            _permittedExtensions, _streamFileLimitSize, ValidateExtension.Encrypt);

                        if (errorModel.Errors.Any())
                        {
                            return(ResponseProvider.Ok(errorModel));
                        }
                        var fileName = FileHelpers.GetFileName(section.ContentDisposition);

                        var fileNameWithEncryptExtension = UploadFileHelper.GetFileNameWithEncryptExtension(fileName, request.EncryptAlg);
                        var uploadFileAbsolutePath       = UploadFileHelper.GetUploadAbsolutePath(_contentRootPath, fileNameWithEncryptExtension, request.Archive);

                        await UploadFile(streamedFileContent, uploadFileAbsolutePath, request.EncryptAlg);
                    }
                }

                section = await reader.ReadNextSectionAsync(cancellationToken);
            }

            return(ResponseProvider.Ok("Upload file successfully"));
        }
Esempio n. 4
0
        public async Task <ResponseModel> Handle(BufferedMultipleFileUploadPhysicalCommand request, CancellationToken cancellationToken)
        {
            var errorModel = new FormFileErrorModel();

            foreach (var formFile in request.Files)
            {
                var formFileContent =
                    await FileHelpers
                    .ProcessFormFile <BufferedMultipleFileUploadPhysical>(
                        formFile, errorModel, _permittedExtensions,
                        _defaultFileSizeLimit);

                if (errorModel.Errors.Any())
                {
                    return(ResponseProvider.Ok(errorModel));
                }

                // For the file name of the uploaded file stored
                // server-side, use Path.GetRandomFileName to generate a safe
                // random file name.

                var filePath = UploadFileHelper.GetUploadAbsolutePath(_contentRootPath, formFile.FileName, request.Archive);
                //var trustedFileNameForFileStorage = Path.GetRandomFileName();
                //var filePath = Path.Combine(
                //    _targetFilePath, trustedFileNameForFileStorage);

                // **WARNING!**
                // In the following example, the file is saved without
                // scanning the file's contents. In most production
                // scenarios, an anti-virus/anti-malware scanner API
                // is used on the file before making the file available
                // for download or for use by other systems.
                // For more information, see the topic that accompanies
                // this sample.

                using (var fileStream = File.Create(filePath))
                {
                    await fileStream.WriteAsync(formFileContent, cancellationToken);

                    // To work directly with the FormFiles, use the following
                    // instead:
                    //await formFile.CopyToAsync(fileStream);
                }
            }
            return(ResponseProvider.Ok("Upload file successful"));
        }
Esempio n. 5
0
        public async Task <ResponseModel> Handle(BufferedSingleFileUploadPhysicalCommand request, CancellationToken cancellationToken)
        {
            var errorModel      = new FormFileErrorModel();
            var formFileContent =
                await FileHelpers.ProcessFormFile <BufferedSingleFileUploadPhysical>(
                    request.File, errorModel, _permittedExtensions,
                    _defaultFileSizeLimit);

            if (errorModel.Errors.Any())
            {
                return(ResponseProvider.Ok(errorModel));
            }

            var filePath = UploadFileHelper.GetUploadAbsolutePath(_contentRootPath, request.File.FileName, request.Archive);

            using (var fileStream = File.Create(filePath))
            {
                await fileStream.WriteAsync(formFileContent, cancellationToken);
            }
            return(ResponseProvider.Ok("Upload file successful"));
        }
        public async Task <ResponseModel <SingleUploadResponse> > Handle(SingleFileUploadPhysicalCommand request, CancellationToken cancellationToken)
        {
            var swTotalEncrypt = new Stopwatch();

            swTotalEncrypt.Start();
            var errorModel = new FormFileErrorModel();

            var multiPartContentTypeValidation = MultiPartContentTypeValidation(_accessor.HttpContext.Request.ContentType)
                                                 .Select(x => x.ErrorMessage)
                                                 .ToArray();

            if (multiPartContentTypeValidation.Any())
            {
                return(ResponseProvider.BadRequest <SingleUploadResponse>(multiPartContentTypeValidation));
            }

            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(_accessor.HttpContext.Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader  = new MultipartReader(boundary, _accessor.HttpContext.Request.Body);
            var section = await reader.ReadNextSectionAsync(cancellationToken);

            while (section != null)
            {
                var hasContentDispositionHeader =
                    ContentDispositionHeaderValue.TryParse(
                        section.ContentDisposition, out var contentDisposition);

                if (hasContentDispositionHeader)
                {
                    var hasFileContentDispositionValidation = HasFileContentDispositionValidation(contentDisposition)
                                                              .Select(x => x.ErrorMessage)
                                                              .ToArray();
                    if (hasFileContentDispositionValidation.Any())
                    {
                        return(ResponseProvider.BadRequest <SingleUploadResponse>(hasFileContentDispositionValidation));
                    }
                    else
                    {
                        var streamedFileContent = await FileHelpers.ProcessStreamedFile(
                            section, contentDisposition, errorModel,
                            _permittedExtensions, _streamFileLimitSize, ValidateExtension.Encrypt);

                        if (errorModel.Errors.Any())
                        {
                            //return ResponseProvider.BadRequest<SingleUploadResponse>(errorModel.Errors);
                            return(ResponseProvider.Ok(new SingleUploadResponse()));
                        }
                        var fileNameWithEncryptExtension = UploadFileHelper.GetFileNameWithEncryptExtension(request.File.FileName, request.EncryptAlg);
                        var uploadFileAbsolutePath       = UploadFileHelper.GetUploadAbsolutePath(_contentRootPath, fileNameWithEncryptExtension, request.Archive);

                        await UploadFile(streamedFileContent, uploadFileAbsolutePath, request.EncryptAlg);
                    }
                }

                section = await reader.ReadNextSectionAsync(cancellationToken);
            }
            swTotalEncrypt.Stop();

            var requestScheme = _accessor.HttpContext.Request.Scheme;
            var domain        = _accessor.HttpContext.Request.Host.Value;
            var url           = Path.Combine(requestScheme, domain, "Archive", request.Archive.ToString(), request.File.FileName);

            Console.Write($"File length: {request.File.Length / 1024f / 1024f} MB");
            Console.WriteLine($"Encrypt time: {swTotalEncrypt.ElapsedMilliseconds}");

            return(ResponseProvider.Ok(new SingleUploadResponse {
                Url = url
            }));
        }