public async Task <ActionResultResponse <Folder> > Insert(string tenantId, string creatorId, string creatorFullName, FolderMeta folderMeta)
        {
            var folder = new Folder
            {
                IdPath = "-1",
                //Order = folderMeta.Order,
                TenantId = tenantId,
                //OrderPath = folderMeta.Order.ToString(),
                CreatorId       = creatorId,
                CreatorFullName = creatorFullName,
                Name            = folderMeta.Name,
                UnsignName      = folderMeta.Name.Trim().StripVietnameseChars().ToUpper()
            };

            if (await _folderRepository.CheckName(tenantId, folder.UnsignName))
            {
                return(new ActionResultResponse <Folder>(-2,
                                                         _fileManagermentResourceResource.GetString("This folder does exists. Please try again.")));
            }

            if (folderMeta.ParentId.HasValue)
            {
                var parentInfo = await _folderRepository.GetInfo(tenantId, creatorId, folderMeta.ParentId.Value);

                if (parentInfo == null)
                {
                    return(new ActionResultResponse <Folder>(-2,
                                                             _fileManagermentResourceResource.GetString("Parent folder does not exists. Please try again.")));
                }

                folder.ParentId = parentInfo.Id;
                folder.IdPath   = $"{parentInfo.IdPath}.-1";
            }

            var result = await _folderRepository.Insert(folder);

            if (result <= 0)
            {
                return(new ActionResultResponse <Folder>(result, _sharedResourceService.GetString(ErrorMessage.SomethingWentWrong)));
            }

            folder.IdPath = folder.IdPath.Replace("-1", folder.Id.ToString());
            await _folderRepository.UpdateFolderIdPath(folder.Id, folder.IdPath);

            return(new ActionResultResponse <Folder>(result, _fileManagermentResourceResource.GetString("Add new folder successful."),
                                                     string.Empty, folder));
        }
Exemple #2
0
        public async Task <ActionResultResponse <List <FileViewModel> > > UploadFiles(string tenantId, string creatorId, string creatorFullName, string creatorAvatar,
                                                                                      int?folderId, IFormFileCollection formFileCollection)
        {
            List <File> listFiles  = new List <File>();
            Folder      folderInfo = null;

            if (folderId.HasValue)
            {
                folderInfo = await _folderRepository.GetInfo(tenantId, creatorId, folderId.Value, true);

                if (folderInfo == null)
                {
                    return(new ActionResultResponse <List <FileViewModel> >(-1,
                                                                            _resourceService.GetString("Folder does not exists. You can not update file to this folder.")));
                }
            }

            foreach (IFormFile formFile in formFileCollection)
            {
                var    concurrencyStamp = Guid.NewGuid().ToString();
                string uploadPath       = $"{CreateFolder()}{concurrencyStamp}.{formFile.GetExtensionFile()}";

                var type           = formFile.GetTypeFile();
                var isImage        = type.Contains("image/");
                var resultCopyFile = await CopyFileToServer(formFile, uploadPath, concurrencyStamp, 0, 0);

                if (isImage && System.IO.File.Exists(uploadPath))
                {
                    System.IO.File.Delete(uploadPath);
                }

                string uploadPathJpeg = $"{CreateFolder()}{concurrencyStamp}Png.Png";
                if (isImage && System.IO.File.Exists(uploadPathJpeg))
                {
                    System.IO.File.Delete(uploadPathJpeg);
                }

                if (resultCopyFile == -1)
                {
                    continue;
                }

                var file = new File
                {
                    ConcurrencyStamp = concurrencyStamp,
                    TenantId         = tenantId,
                    Name             = formFile.FileName,
                    UnsignName       = formFile.FileName.Trim().StripVietnameseChars().ToUpper(),
                    Type             = formFile.GetTypeFile(),
                    Size             = isImage ? resultCopyFile : formFile.GetFileSize(),
                    Url             = isImage ? $"{CreateFolder()}{concurrencyStamp}jpeg.Jpeg" : uploadPath,
                    CreatorId       = creatorId,
                    CreatorFullName = creatorFullName,
                    CreatorAvatar   = creatorAvatar,
                    Extension       = formFile.GetExtensionFile(),
                    FolderId        = folderInfo?.Id,
                };

                // Add file info to list for insert into database.
                listFiles.Add(file);
            }

            var result = await _fileRepository.Insert(listFiles);

            if (result <= 0)
            {
                return(new ActionResultResponse <List <FileViewModel> >(result,
                                                                        _sharedResourceService.GetString("Something went wrong. Please contact with administrator.")));
            }

            return(new ActionResultResponse <List <FileViewModel> >
            {
                Code = 1,
                Message = _resourceService.GetString("Upload file successful"),
                Data = listFiles.Select(x => new FileViewModel
                {
                    Id = x.Id,
                    Name = x.Name,
                    CreatorId = x.CreatorId,
                    CreatorAvatar = x.CreatorAvatar,
                    FolderId = x.FolderId,
                    CreatorFullName = x.CreatorFullName,
                    Url = x.Url,
                    ConcurrencyStamp = x.ConcurrencyStamp,
                    CreateTime = x.CreateTime,
                    Extension = x.Extension,
                    Size = x.Size,
                    Type = x.Type
                }).ToList()
            });

            string CreateFolder()
            {
                var mapPath = _webHostEnvironment.WebRootPath + string.Format("uploads/" + tenantId + "/{0:yyyy/MM/dd}/", DateTime.Now);

                if (!Directory.Exists(mapPath))
                {
                    Directory.CreateDirectory(mapPath);
                }

                return(mapPath);
            }

            async Task <long> CopyFileToServer(IFormFile file, string uploadPath, string concurrencyStamp, int width = 0, int height = 0)
            {
                if (System.IO.File.Exists(uploadPath))
                {
                    return(-1);
                }

                using (var stream = new FileStream(uploadPath, System.IO.FileMode.Create))
                {
                    await file.CopyToAsync(stream);

                    var extension = file.GetExtensionFile();
                    if (extension == "png" || extension == "jpg" || extension == "jpeg" || extension == "gif")
                    {
                        try
                        {
                            using (var sourceImage = Image.FromStream(stream))
                            {
                                var bmPhotoPng = CropImage(sourceImage, width, height, ImageType.Png);
                                using (MemoryStream streamPng = new MemoryStream())
                                {
                                    bmPhotoPng.Save(streamPng, ImageFormat.Png);
                                    streamPng.Seek(0, SeekOrigin.Begin);

                                    string uploadPathPng = $"{CreateFolder()}{concurrencyStamp}Png.Png";

                                    using (FileStream fsPng = new FileStream(uploadPathPng, FileMode.Create, FileAccess.ReadWrite))
                                    {
                                        byte[] bytes = streamPng.ToArray();
                                        fsPng.Write(bytes, 0, bytes.Length);

                                        using (var sourceImagePng = Image.FromStream(fsPng))
                                        {
                                            var bmPhotoJpeg = CropImage(sourceImagePng, 0, 0);

                                            using (MemoryStream streamJpeg = new MemoryStream())
                                            {
                                                bmPhotoJpeg.Save(streamJpeg, ImageFormat.Jpeg);
                                                streamJpeg.Seek(0, SeekOrigin.Begin);

                                                string uploadPathJpeg = $"{CreateFolder()}{concurrencyStamp}jpeg.Jpeg";

                                                using (FileStream fs = new FileStream(uploadPathJpeg, FileMode.Create, FileAccess.ReadWrite))
                                                {
                                                    byte[] bytesJpeg = streamJpeg.ToArray();
                                                    fs.Write(bytesJpeg, 0, bytesJpeg.Length);

                                                    return(bytesJpeg.Length);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            return(-1);
                        }
                    }

                    return(1);
                }
            }
        }