Пример #1
0
        public async Task <IActionResult> UploadUnaccompaniedFile(int userId, FileForUploadDto fileDto, UploadUserParams userParams)
        {
            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            if (currentUserId == 0)
            {
                return(Unauthorized());
            }

            ArrayList returnRows  = new ArrayList();
            IFormFile file        = Request.Form.Files[0];
            string    folderName  = "Upload";
            string    webRootPath = _hostingEnvironment.WebRootPath;
            string    newPath     = System.IO.Path.Combine(webRootPath, folderName);

            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }
            if (file.Length > 0)
            {
                var uploadToAdd = new Upload();
                uploadToAdd.FileName     = fileDto.File.FileName;
                uploadToAdd.DateUploaded = DateTime.Now;
                uploadToAdd.UserId       = currentUserId;
                uploadToAdd.GuestsAdded  = 0;

                int uploadId = await _fileService.AddUpload(uploadToAdd);

                string sFileExtension = System.IO.Path.GetExtension(file.FileName).ToLower();
                string fullPath       = System.IO.Path.Combine(newPath, file.FileName);
                using (var stream = new FileStream(fullPath, FileMode.Create)) {
                    file.CopyTo(stream);
                }

                var sheet   = _fileReader.GetExcelSheet(fullPath);
                var headers = _fileReader.GetExcelSheetHeaders(sheet);

                for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File
                {
                    IRow row = sheet.GetRow(i);
                    if (row == null || row.Cells.All(d => d.CellType == CellType.Blank))
                    {
                        continue;
                    }

                    var rowForUpload = await _fileService.ParseUnaccompaniedExcelRow(row, headers, uploadId);

                    //stay buildingId is nullable
                    if (rowForUpload.RoomId == 0 ||
                        rowForUpload.BuildingId == 0 ||
                        rowForUpload.FirstName == null ||
                        rowForUpload.LastName == null ||
                        rowForUpload.UnitId == 0)
                    {
                        returnRows.Add(rowForUpload);
                    }
                    else
                    {
                        await _fileService.SaveFileRowAsync(rowForUpload);

                        uploadToAdd.GuestsAdded += 1;
                    }
                }

                await _fileService.SaveUpload(uploadToAdd);

                if (System.IO.File.Exists(fullPath))
                {
                    System.IO.File.Delete(fullPath);
                }
            }
            return(Ok(returnRows));
        }