Ejemplo n.º 1
0
        public async Task <ActionResult> Post()
        {
            var    data         = Request.Form.Files["data"];
            string lastModified = Request.Form["lastModified"].ToString();
            var    total        = Request.Form["total"];
            var    fileName     = Request.Form["fileName"];
            var    index        = Request.Form["index"];
            var    fileSize     = long.Parse(Request.Form["fileSize"]);

            string temporaryFile = Path.Combine($"{Directory.GetCurrentDirectory()}/wwwroot/", lastModified);

            try
            {
                if (!Directory.Exists(temporaryFile))
                {
                    Directory.CreateDirectory(temporaryFile);
                }
                string tempPath = Path.Combine(temporaryFile, index.ToString());
                if (!Convert.IsDBNull(data))
                {
                    await FileHelper.CreateFileAsync(data, tempPath);
                }
                bool mergeOk = false;
                if (total == index)
                {
                    var fileExtension = Path.GetExtension(fileName).ToLowerInvariant();
                    fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + fileName;
                    var finalPath = Path.Combine($"{Directory.GetCurrentDirectory()}/wwwroot/", fileName);//最终的文件名(demo中保存的是它上传时候的文件名,实际操作肯定不能这样)
                    mergeOk = await FileHelper.MergeFileAsync(lastModified, finalPath);

                    if (mergeOk)
                    {
                        var saveFile = new Model.FileModel
                        {
                            FileName      = fileName,
                            FilePath      = finalPath,
                            ExtensionName = fileExtension,
                            FileSize      = fileSize
                        };
                        await _fileRepository.AddAsync(saveFile);
                    }
                }

                Dictionary <string, object> result = new Dictionary <string, object>();
                result.Add("number", index);
                result.Add("mergeOk", mergeOk);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                Directory.Delete(temporaryFile);
                throw ex;
            }
        }
Ejemplo n.º 2
0
        public async Task <ResponseUploadFile> UploadFileAsync(IFormFile file, string uploader, bool allowCompress)
        {
            string localFilePath = string.Empty;

            try
            {
                // Store a file into temp disk before proceeding
                localFilePath = await SaveFormFileAsync(file);

                // 1. Check all rules
                foreach (var rule in _fileValidatorRules)
                {
                    await rule.Validate(file, localFilePath);
                }

                // 2. Call Media Connector to upload
                var storedFile = await _fileConnectorExecutions.First(a => a.FileStorageType == _fileOptions.CurrentValue.FileStorageType).StoreFileAsync(file, tempFilePath: localFilePath);

                // 3. Store its into database
                var createdId  = DataUtil.GenerateUniqueId();
                var createFile = new Entities.Files.File
                {
                    Id                = createdId,
                    Name              = file.FileName,
                    DateUploaded      = DateTime.UtcNow,
                    Uploader          = uploader,
                    MIMEType          = await GetFileMIMEType(localFilePath),
                    FileSize          = file.Length,
                    FileStorageType   = _fileOptions.CurrentValue.FileStorageType,
                    IdentifierOptions = storedFile.FileIdentifierOptions,
                    AllowCompress     = allowCompress,
                    DownloadableUrl   = storedFile.UseServerHost
                        ? _filePublishOptions.CurrentValue.DownloadableHost + "/" + createdId
                            : storedFile.DownloadableUrl
                };

                await _fileRepository.AddAsync(createFile);

                System.IO.File.Delete(localFilePath);
                return(new ResponseUploadFile
                {
                    FileId = createFile.Id,
                    DownloadableUrl = createFile.DownloadableUrl
                });
            }
            finally
            {
                if (!string.IsNullOrEmpty(localFilePath))
                {
                    System.IO.File.Delete(localFilePath);
                }
            }
        }
Ejemplo n.º 3
0
        public async Task <OutgoingFile> SaveAsync(string fileName, byte[] fileContents)
        {
            try
            {
                var filePath = await _fileStorage.SaveAsync(fileName, fileContents);

                var incomingFile = new IncomingFile
                {
                    AddedOn  = DateTime.UtcNow,
                    FileName = fileName,
                    Path     = filePath,
                    Size     = fileContents.Length
                };

                var incomingFileEntity = _mapper.Map <File>(incomingFile);

                var outgoingFileEntity = await _repository.AddAsync(incomingFileEntity);

                var outgoingFile = _mapper.Map <OutgoingFile>(outgoingFileEntity);

                return(outgoingFile);
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Unable to save {fileName}: {e.Message}");
                throw;
            }
        }
Ejemplo n.º 4
0
        public async Task <AvatarDTO> Save(IFormFile formFile)
        {
            var credentials = new BasicAWSCredentials(_configuration["AwsSettings:AccessKey"], _configuration["AwsSettings:SecretKey"]);

            s3Client = new AmazonS3Client(credentials, RegionEndpoint.SAEast1);
            string fileName  = formFile.FileName;
            string objectKey = $"{_configuration["AwsSettings:FolderName"]}/{fileName}";
            string url       = "";

            using (Stream fileToUpload = formFile.OpenReadStream())
            {
                var putObjectRequest = new PutObjectRequest();
                putObjectRequest.BucketName  = _configuration["AwsSettings:BucketName"];
                putObjectRequest.Key         = objectKey;
                putObjectRequest.InputStream = fileToUpload;
                putObjectRequest.ContentType = formFile.ContentType;

                var response = await s3Client.PutObjectAsync(putObjectRequest);

                url = GeneratePreSignedURL(objectKey);
            }
            Avatar avatarSaved = await _fileRepository.AddAsync(new Avatar {
                Name = fileName,
                Url  = url
            });

            AvatarDTO dto = _mapper.Map <AvatarDTO>(avatarSaved);

            return(dto);
        }
Ejemplo n.º 5
0
        public async Task <Guid?> AddOrUpdateFileByIdAsync(IFormFile image, Guid?iconId, CancellationToken cancellationToken)
        {
            if (image == null)
            {
                return(iconId);
            }

            await using var memory = new System.IO.MemoryStream();
            await image.CopyToAsync(memory, cancellationToken);

            if (iconId.HasValue)
            {
                await _fileRepository.Delete(iconId.Value, cancellationToken);
            }

            var file = new File
            {
                Data        = memory.ToArray(),
                ContentType = image.ContentType
            };
            await _fileRepository.AddAsync(file, cancellationToken);

            await _unitOfWork.SaveChangesAsync(cancellationToken);

            return(file.Id);
        }
Ejemplo n.º 6
0
        public async Task <Unit> Handle(AddFileCommand request, CancellationToken cancellationToken)
        {
            var fileId = await _fileRepository.AddAsync(request.Filename, request.Content.ToArray(), cancellationToken);

            request.FileId = fileId;

            await _userRepository.AssignFileAsync(request.Username, request.FileId, UserFileStatus.Owner, cancellationToken);

            return(Unit.Value);
        }
Ejemplo n.º 7
0
        public async Task <DocumentInfo> UploadFileAsync(UserFile file, Guid authorId, string host)
        {
            var filePath = await _diskFileService.UploadAsync(file, GetStoragePath());

            var document = new File
            {
                AuthorId           = authorId,
                DownloadLink       = $"{host}/api/files/download/{filePath}",
                IsFilePathAbsolute = false,
                Name         = filePath.Split("/").Last(),
                FriendlyName = file.FriendlyName
            };

            var savedDocument = await _fileRepository.AddAsync(document);

            return(_mapper.Map <DocumentInfo>(savedDocument));
        }
Ejemplo n.º 8
0
        private async Task <FileDto> AddFileAsync(FileDto fileToAdd)
        {
            var result = _mapper.Map <FileDto, BlueprintFile>(fileToAdd);

            result.CreatedDate = DateTime.UtcNow;

            if (!_configuration.FileTypes.Contains(fileToAdd.Extension))
            {
                result.BackgroudProcessingStatus = (int?)BackgroudProcessingStatus.Processed;
            }

            await _fileRepository.AddAsync(result);

            await _fileRepository.CommitAsync();

            return(_mapper.Map <BlueprintFile, FileDto>(result));
        }
Ejemplo n.º 9
0
        public async Task <IFile> AddFileAsync(IFolder folder, string name, string contentType, Stream binary)
        {
            if (folder == null)
            {
                throw new ArgumentNullException(nameof(folder));
            }

            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (name.Contains("/"))
            {
                throw new ArgumentException("Cannot use path delimiter('/')", nameof(name));
            }

            if (string.IsNullOrEmpty(contentType))
            {
                throw new ArgumentNullException(nameof(contentType));
            }

            if (binary == null)
            {
                throw new ArgumentNullException(nameof(binary));
            }

            var userId = _resolver.GetUserId();

            if (userId == null)
            {
                throw new UnauthorizedAccessException();
            }

            var path = CreateBinaryPath();

            using (var stream = SysFile.OpenWrite(path))
            {
                await binary.CopyToAsync(stream);
            }
            var size = new FileInfo(path).Length;
            var file = await _files.AddAsync(folder.Id, name, path, contentType, size, userId, DateTimeOffset.UtcNow);

            return(Mapping.Mapper.Map <File>(file));
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> UploadAsync([FromForm] FileDataDTO fileData)
        {
            try
            {
                int maxSize = Convert.ToInt32(config["AppDetails:AllowedFileSizeInMb"]) * 1000000;

                if (fileData.File.Length > maxSize)
                {
                    return(BadRequest("File is too big"));
                }

                string[] alloweFileTypes = config["AppDetails:AllowedFileTypes"].Split(",");

                string extension = Path.GetExtension(fileData.File.FileName);

                if (!alloweFileTypes.Contains(extension))
                {
                    return(BadRequest("File extension is not allowed"));
                }

                string path = await fileService.SaveOnDriveAsync(fileData.File);

                if (path == null)
                {
                    // Such file already exists
                    return(BadRequest("File with such name already exists"));
                }

                var fileInstance = await fileRepository.AddAsync(new FileInstance()
                {
                    Name            = fileData.File.FileName,
                    SizeInMb        = (double)fileData.File.Length / 1000000,
                    Path            = path,
                    UploadDate      = DateTime.Now,
                    UserWhoUploaded = fileData.UserWhoUploaded
                });

                return(Ok(fileInstance));
            }
            catch (Exception e)
            {
                // place to add logging
                return(StatusCode(StatusCodes.Status500InternalServerError, e.Message));
            }
        }
Ejemplo n.º 11
0
        public async Task <Unit> Handle(AddShareCommand request, CancellationToken cancellationToken)
        {
            var user = await _userRepository.FirstOrDefaultAsync(request.Sender, cancellationToken);

            if (user.PrivateKeyPassword != request.PrivateKeyPassword.Sha512())
            {
                throw new Exception("Invalid private key password");
            }

            var decryptionResponse = _encryptor.Decrypt(user.PrivateKey, request.PrivateKeyPassword.Sha256AsBytes());

            if (decryptionResponse.Status == Status.Failed)
            {
                throw new Exception();
            }

            request.Id = await _shareRepository.AddShareAsync(request.Title, request.Description, cancellationToken);

            await _shareRepository.AddShareUserAsync(request.Id, request.Sender, ShareUserOwnershipStatus.Sender, cancellationToken);

            foreach (var receiver in request.Receivers)
            {
                await _shareRepository.AddShareUserAsync(request.Id, receiver, ShareUserOwnershipStatus.Receiver, cancellationToken);
            }

            foreach (var file in request.Files)
            {
                var fileId = await _fileRepository.AddAsync(file.Name, file.Content, cancellationToken);

                await _userRepository.AssignFileAsync(request.Sender, fileId, UserFileStatus.Owner, cancellationToken);

                await _shareRepository.AddShareFileAsync(request.Id, fileId, cancellationToken);

                var signResponse = await _ecdsa.SignFileAsync(file.Name, file.Content, decryptionResponse.DecryptedText);

                await _shareRepository.AddShareFileUserAsync(request.Id, fileId, request.Sender,
                                                             signResponse.Signature, cancellationToken);
            }

            await _shareRepository.AcceptAsync(request.Id, request.Sender);

            return(Unit.Value);
        }
Ejemplo n.º 12
0
        public async Task AddPhotoAsync(string path, Guid id, IFormFile photo)
        {
            var @user = await _userRepository.GetAsync(id);

            int width        = 0;
            var productImage = Image.Load(photo.OpenReadStream());
            int div          = productImage.Height / 256;
            int hight        = productImage.Height / div;

            if (productImage.Height < productImage.Width)
            {
                width = 256;
            }
            else
            {
                width = productImage.Width / div;
            }
            productImage.Mutate(x => x.Resize(width, hight));
            await _fileRepository.AddAsync(productImage, path, user.Id);

            user.SetImageLocation(Path.Combine(path + "\\uploads\\" + user.Id + ".png"));
            await _userRepository.UpdateAsync(@user);
        }
Ejemplo n.º 13
0
        public async Task AddPhotoAsync(string path, Guid id, IFormFile photo)
        {
            var @product = await _productRepository.GetOrFailAsync(id);

            int width        = 0;
            var productImage = Image.Load(photo.OpenReadStream());
            int div          = productImage.Height / 512;
            int hight        = productImage.Height / div;

            if (productImage.Height < 2 * productImage.Width)
            {
                width = 1024;
            }
            else
            {
                width = productImage.Width / div;
            }
            productImage.Mutate(x => x.Resize(width, hight));
            await _fileRepository.AddAsync(productImage, path, product.Id);

            @product.SetImageLocation(Path.Combine(path + "\\uploads\\" + product.Id + ".png"));
            await _productRepository.UpdateAsync(@product);
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> Upload(string folder, List <IFormFile> files)
        {
            var resources = new List <string>();

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    var resourceId = Guid.NewGuid().ToString();
                    resources.Add(resourceId);

                    await _fileRepository.AddAsync(new GenericFile(formFile.CopyToAsync)
                    {
                        Folder      = folder,
                        ContentType = formFile.ContentType,
                        Name        = formFile.FileName,
                        ResourceId  = resourceId
                    });
                }
            }

            return(Created(Url.Content("~/drive/file"), resources));
        }
Ejemplo n.º 15
0
        public async Task <IResultModel> Add(FileUploadModel model, FileInfo fileInfo)
        {
            var entity = new FileEntity
            {
                ModuleCode = model.ModuleCode,
                Group      = model.Group,
                AccessMode = model.AccessMode,
                FileName   = fileInfo.FileName,
                SaveId     = fileInfo.SaveName.Split('.')[0],
                Path       = fileInfo.Path,
                FullPath   = fileInfo.FullPath,
                Ext        = fileInfo.Ext,
                Size       = fileInfo.Size.Size,
                SizeName   = fileInfo.Size.ToString(),
                Md5        = fileInfo.Md5
            };

            var mime = await _mimeRepository.Get(fileInfo.Ext.ToLower());

            if (mime != null)
            {
                entity.Mime = mime.Value;
            }

            using var uow = _dbContext.NewUnitOfWork();
            var result = await _repository.AddAsync(entity, uow);

            if (result)
            {
                #region ==绑定文件拥有者==

                if (model.AccessMode == FileAccessMode.Auth && model.Accounts != null && model.Accounts.Any())
                {
                    var owners = model.Accounts.Split(',')
                                 .Select(accountId => new FileOwnerEntity
                    {
                        SaveId    = entity.SaveId,
                        AccountId = Guid.Parse(accountId)
                    }).ToList();
                    await _ownerRepository.AddAsync(owners, uow);
                }

                #endregion

                #region ==OSS上传==

                var fileObject = new FileObject
                {
                    ModuleCode   = entity.ModuleCode,
                    Group        = entity.Group,
                    AccessMode   = entity.AccessMode,
                    PhysicalPath = model.PhysicalPath,
                    FileInfo     = fileInfo
                };

                await _fileStorageProvider.Upload(fileObject);

                entity.Url = fileInfo.Url;

                #endregion

                uow.Commit();

                return(ResultModel.Success(entity));
            }
            return(ResultModel.Failed());
        }
Ejemplo n.º 16
0
        public async Task <File> AddAsync(int torrentId, IFormFile file)
        {
            Guard.Against.NullInvalid(file, "Invalid file");

            if (string.IsNullOrWhiteSpace(file.FileName))
            {
                throw new RutrackerException(
                          "The file name cannot be empty.",
                          ExceptionEventTypes.InvalidParameters);
            }

            if (file.Length > _fileOptions.MaxSize)
            {
                throw new RutrackerException(
                          $"File '{file.Name}' is too large (more {_fileOptions.MaxSize} bytes).",
                          ExceptionEventTypes.InvalidParameters);
            }

            var torrent = await _torrentRepository.GetAsync(torrentId);

            if (torrent == null)
            {
                throw new RutrackerException(
                          $"The torrent with '{torrentId}' not found",
                          ExceptionEventTypes.InvalidParameters);
            }

            if (torrent.IsStockTorrent)
            {
                throw new RutrackerException(
                          "Cannot add the file to the stock torrent.",
                          ExceptionEventTypes.InvalidParameters);
            }

            var result = await _fileRepository.AddAsync(new File
            {
                Name      = file.FileName,
                BlobName  = $"{Path.GetFileNameWithoutExtension(file.FileName)}-{Guid.NewGuid():N}{Path.GetExtension(file.FileName)}",
                Size      = file.Length,
                Type      = file.ContentType,
                TorrentId = torrentId
            });

            await _unitOfWork.SaveChangesAsync();

            var containerName = torrentId.ToString().PadLeft(10, '0');
            var fileName      = result.BlobName;
            var contentType   = result.Type;
            var stream        = file.OpenReadStream();

            var url = await _storageService.UploadFileAsync(containerName, fileName, contentType, stream);

            result.Url    = url;
            torrent.Size += result.Size;

            _fileRepository.Update(result);
            _torrentRepository.Update(torrent);

            await _unitOfWork.SaveChangesAsync();

            return(result);
        }
        public async Task <bool> Handle(ResizeImageCommand request, CancellationToken cancellationToken)
        {
            var criteria          = new ImageResizeCriteria(request.ImageId, request.Query);
            var criteriaValidator = new ImageResizeCriteriaValidator(_configuration);

            Guard.AgainstInvalidArgumentWithMessage("Invalid criteria", criteriaValidator.ValidCriteria(criteria));

            (int?width, int?height)widthHeightPair = criteriaValidator.GetCriteria(criteria);

            var files = _fileRepository.GetFiles(criteria.ImageId, widthHeightPair.width, widthHeightPair.height);

            Guard.AgainstNullOrNotAny("Files", files);

            var originalImage = files.FirstOrDefault(file => file.Id == request.ImageId);

            Guard.AgainstNull("OriginalFile", originalImage);

            //if request has no param -> ask for original image -> return directly to original image
            if (criteria.Empty)
            {
                return(true);
            }

            //resized image is always the first one in the list
            var fileResized = files.OrderByDescending(file => file.OriginalId)
                              .FirstOrDefault();

            bool canResize = _imageService.CanResize(widthHeightPair, (fileResized.Width, fileResized.Height));

            Guard.AgainstInvalidOperationWithMessage("Cannot Resize this picture with given resolution", canResize);

            bool shouldResize = _imageService.ShouldResize(((int)originalImage.Width, (int)originalImage.Height), widthHeightPair);

            if (!shouldResize)
            {
                return(true);
            }

            //file not exist
            if (fileResized.OriginalId == null)
            {
                if ((widthHeightPair.width == null || fileResized.Width == widthHeightPair.width) &&
                    (widthHeightPair.height == null || fileResized.Height == widthHeightPair.height))
                {
                    return(true);
                }

                using (var imageData = _imageService.ReadImage(fileResized.FilePath))
                {
                    var    oldFileName   = Path.GetFileName(fileResized.FilePath);
                    string fileExtension = Path.GetExtension(fileResized.FilePath);
                    var    imagePath     = Path.GetDirectoryName(fileResized.FilePath);

                    var newFileName = string.Concat(Path.GetFileNameWithoutExtension(oldFileName),
                                                    widthHeightPair.width == null ? "" : $"_w{widthHeightPair.width}",
                                                    widthHeightPair.height == null ? "" : $"_h{widthHeightPair.height}",
                                                    fileExtension);

                    string cloudPath = PathHelper.CombineUrl(imagePath.Replace(_configuration.RootDataFolder, _configuration.CloudDataUrl), string.Empty);

                    using (FileStream outputStream = new FileStream(Path.Combine(imagePath, newFileName), FileMode.CreateNew))
                    {
                        (int?width, int?height)sizeAfterResized = await _imageService.ResizeImage(imageData, (widthHeightPair.width, widthHeightPair.height), fileExtension, outputStream);

                        var filebuilder = new FileBuilder();
                        var newFile     = filebuilder.BuildCloudUrl(cloudPath, newFileName)
                                          .BuildFilePath(imagePath, newFileName)
                                          .BuildFileInfo(new BlueprintFile
                        {
                            CreatedDate      = DateTime.UtcNow,
                            CreatedBy        = nameof(System),
                            FileType         = fileResized.FileType,
                            Height           = sizeAfterResized.height,
                            Width            = sizeAfterResized.width,
                            OriginalFileName = newFileName,
                            Source           = fileResized.Source,
                            OriginalId       = fileResized.Id,
                            Extension        = fileResized.Extension,
                            CompanyId        = fileResized.CompanyId
                        })
                                          .Build();

                        await _fileRepository.AddAsync(newFile);

                        await _fileRepository.CommitAsync();

                        return(true);
                    }
                }
            }
            return(true);
        }