Пример #1
0
        public IRestResponse <FileMessage> Upload(UploadInput input)
        {
            try
            {
                //LogInput(input);

                var req = new RestRequest("upload", Method.POST);
                req.AddFile(input.FileType, input.Data, input.FileName, input.MimeType);
                req.AlwaysMultipartFormData = true;

                req.AddParameter("reply_keyboard", input.ReplyKeyboard);
                req.AddParameter("inline_keyboard", input.InlineKeyboard);

                var response = RestApi.Execute <FileMessage>(req);

                LogOutput(response, new
                {
                    hasData = response.Data != null,
                    method  = "Upload",
                    input.FileName
                });

                return(response);
            }
            catch (Exception ex)
            {
                Logger.Log("Upload", LogErrorLevel.Error, ex);
                return(null);
            }
        }
Пример #2
0
        public ActionResult <UploadResult> UploadDocument([FromForm] UploadInput input)
        {
            var filePath = Path.GetTempFileName();

            if (input.email == null || input.email.Trim().Equals(""))
            {
                return(new UploadResult {
                    success = false,
                    message = "Please provide email."
                });
            }

            if (!emailChecker.IsValid(input.email.Trim()))
            {
                return(new UploadResult {
                    success = false,
                    message = $"{input.email.Trim()} is an invalid email."
                });
            }

            if (input.file != null && input.file.Length > 0)
            {
                // Could swap out parser based on document type (hubdoc etc.)
                // Document type could be user specified or deduced?
                HDInvoiceParser parser   = new HDInvoiceParser();
                Document        document = null;

                try {
                    document = parser.Parse(input.file.FileName, input.file.OpenReadStream());
                    document.uploadedTimeStamp = DateTime.Now;
                    document.uploadedBy        = input.email.Trim();
                    document.fileSize          = input.file.Length;
                } catch (Exception e) {
                    Debug.WriteLine(e);
                    return(new UploadResult {
                        success = false,
                        message = "File might be invalid, please verify tempalte configuration."
                    });
                }

                long newId = DocumentStore.Instance.AddDocument(document);

                return(new UploadResult {
                    id = newId,
                    success = true
                });
            }
            else
            {
                return(new UploadResult {
                    success = false,
                    message = "File is empty."
                });
            }
        }
Пример #3
0
        public async Task <ActionResult <ResponseData <FileItemDto> > > UploadFileAsync(Guid groupId, string storeId, string fileName, bool depGroup = false)
        {
            try
            {
                if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(storeId) || Guid.Empty.Equals(groupId))
                {
                    return(ResponseData <FileItemDto> .BuildFailedResponse(message : "参数错误"));
                }
                var uploaderId = GetEmployeeId();
                var group      = !depGroup
                    ? await _groupAppService.GetByIdAsync(groupId)
                    : await _departmentAppService.GetDepGroupByIdAsync(groupId);

                if (group == null)
                {
                    return(ResponseData <FileItemDto> .BuildFailedResponse(message : "群组不存在"));
                }
                if (!IsMemeberInGroup(group.Members, uploaderId))
                {
                    return(ResponseData <FileItemDto> .BuildFailedResponse(message : "无上传权限"));
                }
                var attachment = await _attachmentAppServiceFactory(storeId).GetByIdAsync(storeId);

                if (attachment == null)
                {
                    return(ResponseData <FileItemDto> .BuildFailedResponse(message : "文件上传失败"));
                }
                var input = new UploadInput
                {
                    FileName = fileName,
                    GroupId  = groupId,
                    StoreId  = storeId
                };
                await SendMessageAsync(groupId, GetUserId(), fileName, attachment);

                var result = await _groupFileControlApp.UploadFileAsync(input, uploaderId);

                _cache.Remove(groupId);
                if (result != null)
                {
                    result.Size         = attachment.Size;
                    result.UploaderName = GetUserFullName();
                    return(ResponseData <FileItemDto> .BuildSuccessResponse(result));
                }
                else
                {
                    return(ResponseData <FileItemDto> .BuildFailedResponse());
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(LogError(_logger, ex)));
            }
        }
Пример #4
0
        public async Task Upload([FromForm] UploadInput input, [FromServices] IFileVerifier fileVerifier)
        {
            var fileInfo = fileInfoProvider.GetFileInfo(input.File, HttpContext.Request.PathBase);

            using (var uploadStream = input.Content.OpenReadStream())
            {
                fileVerifier.Validate(uploadStream, fileInfo.DerivedFileName, input.Content.ContentType);
                using (Stream stream = fileFinder.WriteFile(fileInfo.DerivedFileName))
                {
                    await uploadStream.CopyToAsync(stream);
                }
            }
        }
Пример #5
0
        public async Task Error_IfCredentialsAreInvalidAndThrowExceptionOnErrorResponseIsFalse()
        {
            var input = new UploadInput
            {
                FileMask    = "TestFile1.csv",
                FilePath    = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"../../../TestData/"),
                S3Directory = @"\"
            };

            var options = new UploadOptions
            {
                ReturnListOfObjectKeys = true,
                ThrowErrorIfNoMatch    = true
            };

            var param = new Parameters
            {
                // Invalid AwsAccesKeyId.
                AwsAccessKeyId = "fnvfdvfkdjvn",

                // Invalid AwsSecretAccessKey.
                AwsSecretAccessKey            = "bvfjhbvdjhvbjdhf",
                BucketName                    = Environment.GetEnvironmentVariable("HiQ_AWSS3Test_BucketName"),
                Region                        = (Regions)int.Parse(Environment.GetEnvironmentVariable("HiQ_AWSS3Test_Region")),
                ThrowExceptionOnErrorResponse = false
            };

            async Task <List <string> > UploadThatThrows()
            {
                var response = await UploadTask.UploadFiles(input, param, options, new CancellationToken());

                return(response);
            }

            try
            {
                await UploadThatThrows();
            }
            catch (Exception ex)
            {
                Assert.Fail("Expected no exception, but got: " + ex.Message);
            }
        }
Пример #6
0
        public async Task <FileItemDto> UploadFileAsync(UploadInput param, Guid uploaderId)
        {
            using (var db = new ServiceDbContext(_dbContextOptions))
            {
                var fileItem = new FileItem
                {
                    Id             = Guid.NewGuid(),
                    DownloadAmount = 0,
                    GroupId        = param.GroupId,
                    Name           = param.FileName,
                    StoreId        = param.StoreId,
                    UpdatedOn      = DateTimeOffset.UtcNow,
                    UploaderId     = uploaderId,
                };
                await db.FileItems.AddAsync(fileItem);

                await db.SaveChangesAsync();

                return(_mapper.Map <FileItemDto>(fileItem));
            }
        }
Пример #7
0
        public void Error_IfSourcePathIsInvalid()
        {
            var input = new UploadInput
            {
                FileMask = @"*.test",
                FilePath = @"c:\there_is_no_folder_like_this\"
            };
            var options = new UploadOptions
            {
                ReturnListOfObjectKeys = true,
                ThrowErrorIfNoMatch    = true
            };

            void UploadThatThrows()
            {
                UploadTask.UploadFiles(input, _param, options, new CancellationToken());
            }

            Assert.That(UploadThatThrows,
                        Throws.TypeOf <ArgumentException>()
                        .With.Message.StartsWith("Source path not found."));
        }
Пример #8
0
        public void Error_IfCredentialsAreInvalidAndThrowExceptionOnErrorResponseIsTrue()
        {
            var input = new UploadInput
            {
                FileMask    = "TestFile1.csv",
                FilePath    = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"../../../TestData/"),
                S3Directory = @"\",
                CannedACL   = S3CannedACLs.Private
            };

            var options = new UploadOptions
            {
                ReturnListOfObjectKeys = true,
                ThrowErrorIfNoMatch    = true
            };

            var param = new Parameters
            {
                // Invalid AwsAccesKeyId.
                AwsAccessKeyId = "fnvfdvfkdjvn",

                // Invalid AwsSecretAccessKey.
                AwsSecretAccessKey            = "bvfjhbvdjhvbjdhf",
                BucketName                    = Environment.GetEnvironmentVariable("HiQ_AWSS3Test_BucketName"),
                Region                        = (Regions)int.Parse(Environment.GetEnvironmentVariable("HiQ_AWSS3Test_Region")),
                ThrowExceptionOnErrorResponse = true
            };

            async Task <List <string> > UploadThatThrows()
            {
                var response = await UploadTask.UploadFiles(input, param, options, new CancellationToken());

                return(response);
            }

            Assert.That(UploadThatThrows, Throws.TypeOf <SecurityException>().With.Message.StartsWith("Invalid Amazon S3 Credentials - data was not uploaded."));
        }
Пример #9
0
        public void Error_IfSwitchIsOnAndNothingMatches()
        {
            var input = new UploadInput
            {
                FileMask    = "there_is_no_spoon.text",
                FilePath    = Path.GetTempPath(),
                S3Directory = @"\"
            };

            var options = new UploadOptions
            {
                ReturnListOfObjectKeys = true,
                ThrowErrorIfNoMatch    = true
            };

            void UploadThatThrows()
            {
                UploadTask.UploadFiles(input, _param, options, new CancellationToken());
            }

            Assert.That(UploadThatThrows,
                        Throws.TypeOf <ArgumentException>()
                        .With.Message.StartsWith("No files match the filemask within supplied path."));
        }
        public ActionResult Upload(UploadInput input)
        {
            if (!ModelState.IsValid)
            {
                return(View(input));
            }

            try
            {
                using (var streamReader = new StreamReader(input.RectanglesFile.InputStream))
                {
                    var rectanglesString = streamReader.ReadToEnd();
                    var grid             = gridService.InitialiseGridFromString(rectanglesString);

                    var model = new SolutionRectanglesDisplay(grid, grid.GetMinimumVerticallyStackedRectangles());
                    return(View("Solution", model));
                }
            }
            catch (LogicException ex)
            {
                ModelState.AddLogicErrors(ex);
                return(View(input));
            }
        }
        public ActionResult Upload()
        {
            var model = new UploadInput();

            return(View(model));
        }
Пример #12
0
        public JsonResult Upload(UploadInput input)
        {
            myFileService.Upload(input);

            return(Json(new { msg = "success" }));
        }
Пример #13
0
        public int Upload(UploadInput input)
        {
            var userId   = HttpContext.Current.Session["UserID"].ToString();
            var userName = HttpContext.Current.Session["UserName"].ToString();

            UserDto userDto = new UserDto
            {
                UserID   = userId,
                UserName = userName
            };

            userService.SaveUser(userDto);

            PersonalFile personalFile = _context.PersonalFiles.FirstOrDefault(a => a.Id == input.Id);

            DocumentInfo documentInfo = null;

            CreateDocumentInput createDocumentInput = new CreateDocumentInput
            {
                CreateUserID   = userId,
                CreateUserName = userName,
                FileName       = input.FileName + "." + input.FileType,
                FileType       = input.FileType
            };

            //新建文件
            if (input.CreateType == CreateType.newFile.ToString() && (personalFile == null || input.FileType != personalFile.FileType))
            {
                MemoryStream stream = new MemoryStream();
                if (input.FileType == FileType.xlsx.ToString())
                {
                    stream = new MemoryStream(NPOIHelper.CreateExcelFile());
                }
                documentInfo = documentService.CreateDocument(createDocumentInput, stream);
            }
            else if (input.CreateType == CreateType.uploadFile.ToString() && (personalFile == null || HttpContext.Current.Request.Files.Count > 0))
            {
                if (HttpContext.Current.Request.Files.Count == 0)
                {
                    return(-1);
                }

                var uploadFile = HttpContext.Current.Request.Files[0];
                createDocumentInput.FileName = uploadFile.FileName;
                createDocumentInput.FileType = createDocumentInput.FileName.Substring(createDocumentInput.FileName.LastIndexOf('.') + 1);
                input.FileName = createDocumentInput.FileName.Substring(0, createDocumentInput.FileName.LastIndexOf('.'));
                if (createDocumentInput.FileType == FileType.doc.ToString() || createDocumentInput.FileType == FileType.docx.ToString())
                {
                    input.FileType = FileType.docx.ToString();
                }
                else
                {
                    input.FileType = FileType.xlsx.ToString();
                }

                documentInfo = documentService.CreateDocument(createDocumentInput, uploadFile.InputStream);
            }

            if (personalFile == null)
            {
                var createTime = DateTime.Now;
                personalFile = new PersonalFile
                {
                    DocumentID     = documentInfo.Id,
                    CreateType     = input.CreateType,
                    FileName       = input.FileName,
                    FileType       = input.FileType,
                    CreateUserID   = userId,
                    CreateUserName = userName,
                    CreateTime     = createTime,
                    ModifyUserID   = userId,
                    ModifyUserName = userName,
                    ModifyTime     = createTime
                };
                _context.PersonalFiles.Add(personalFile);
            }
            else
            {
                //personalFile.CreateType = input.CreateType;
                personalFile.FileName = input.FileName;
                //personalFile.FileType = input.FileType;
                documentInfo          = _context.DocumentInfos.FirstOrDefault(a => a.Id == personalFile.DocumentID);
                documentInfo.FileName = input.FileName + "." + personalFile.FileType;
            }

            _context.SaveChanges();

            var shareUserList = JsonConvert.DeserializeObject <List <FileUserDto> >(input.ShareUserList);

            fileShareService.AddShareUser(new AddShareUserInput
            {
                FileId       = personalFile.Id,
                FileUserDtos = shareUserList
            });

            return(personalFile.Id);
        }