Beispiel #1
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="isCompressImage">是否需要压缩图片</param>
        /// <returns></returns>
        private async Task <UploadResult> Upload(HttpContent fileContent)
        {
            UploadResult uploadResult        = null;
            var          userClaimsInfoModel = this.GetUserModelFromCurrentClaimsIdentity();

            string fileName    = fileContent.Headers.ContentDisposition.FileName.Trim('"');
            string newFileName = string.Concat(
                DateTime.Now.ToString("yyyyMMdd"), "_", Guid.NewGuid().ToString(), "_", fileName);
            var saveBytes = await fileContent.ReadAsByteArrayAsync();

            //暂时性先放到一个文件夹下面去
            string fileID = _fileService.UploadFile(newFileName, saveBytes);



            string token = Guid.NewGuid().ToString();
            AttachmentUploadModel attachmentUploadModel = new AttachmentUploadModel();

            attachmentUploadModel.fileID   = fileID;
            attachmentUploadModel.userMail = userClaimsInfoModel.mail;
            if (await _attachmentUploadRepository.InsertAttachmentUploadToken(token, attachmentUploadModel, new TimeSpan(1, 0, 0)))
            {
                uploadResult             = new UploadResult();
                uploadResult.uploadToken = token;
            }

            return(uploadResult);
        }
Beispiel #2
0
        public async Task <IResultModel> Upload([FromForm] AttachmentUploadModel model, IFormFile formFile)
        {
            model.AccountId = _loginInfo.AccountId;
            var uploadModel = new FileUploadModel
            {
                Request  = Request,
                FormFile = formFile,
                RootPath = _moduleCommonOptions.UploadPath,
                Module   = "Common",
                Group    = Path.Combine("Attachment", model.Module, model.Group)
            };

            //附件存储路径/Common/Attachment/{所属模块名称}/{所属分组模块}
            var result = await _fileUploadHelper.Upload(uploadModel);

            if (result.Successful)
            {
                var resultModel = await _service.Upload(model, result.Data);

                if (resultModel.Successful)
                {
                    var url = Request.GetHost($"/common/attachment/download/{resultModel.Data.Id}");
                    resultModel.Data.Url = new Uri(url).ToString();
                    return(ResultModel.Success(resultModel));
                }
            }

            return(ResultModel.Failed("上传失败"));
        }
Beispiel #3
0
        public async Task <IResultModel <AttachmentUploadResultModel> > Upload(AttachmentUploadModel model, FileInfo fileInfo)
        {
            var result = new ResultModel <AttachmentUploadResultModel>();

            var entity = new AttachmentEntity
            {
                FileName = model.Name.NotNull() ? model.Name : fileInfo.FileName,
                SaveName = fileInfo.SaveName,
                Ext      = fileInfo.Ext,
                Md5      = fileInfo.Md5,
                Path     = fileInfo.Path,
                FullPath = Path.Combine(fileInfo.Path, fileInfo.SaveName),
                Size     = fileInfo.Size.Size,
                SizeCn   = fileInfo.Size.ToString(),

                Module = model.Module,
                Group  = model.Group
            };

            var media = await _mediaTypeRepository.FirstAsync(m => m.Ext == fileInfo.Ext);

            entity.MediaType = media?.Value;

            if (await _attachmentRepository.InsertAsync(entity))
            {
                var resultModel = _mapper.Map <AttachmentUploadResultModel>(entity);
                return(result.Success(resultModel));
            }

            return(result.Failed("上传失败"));
        }
        public async Task <IResultModel> Upload([FromForm] AttachmentUploadModel model, IFormFile formFile)
        {
            var uploadModel = new FileUploadModel
            {
                Request  = Request,
                FormFile = formFile,
                RootPath = Path.Combine(AppContext.BaseDirectory, _webConfig.UploadPath),
                Module   = model.Module,
                Group    = model.Group
            };

            var result = await FileUploadHelper.Upload(uploadModel);

            if (result.Successful)
            {
                var resultModel = await _service.Upload(model, result.Data);

                if (resultModel.Successful)
                {
                    var url = Request.GetHost($"/admin/attachment/download/{resultModel.Data.Id}");
                    resultModel.Data.Url = new Uri(url).ToString();
                    return(ResultModel.Success(resultModel));
                }
            }

            return(ResultModel.Failed("上传失败"));
        }
Beispiel #5
0
        public async Task <bool> InsertAttachmentUploadToken(string token, AttachmentUploadModel attachmentUploadModel, TimeSpan?expiry)
        {
            Enforce.ArgumentNotNull <string>(token, "Upload Token 不能为null");
            Enforce.ArgumentNotNull <AttachmentUploadModel>(attachmentUploadModel, "AttachmentUploadModel 不能为null");

            string key    = string.Concat(prefix, token);
            string value  = Newtonsoft.Json.JsonConvert.SerializeObject(attachmentUploadModel);
            bool   result = await database.StringSetAsync(key, value, expiry);

            return(result);
        }
        /// <inheritdoc cref="Upload"/>
        public async Task <ApiResult <bool> > UploadAsync(AttachmentUploadModel model, CancellationToken cancellationToken = default)
        {
            if (model is null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var resource = ResourceUrl + $"{model.DocumentId}/{model.DocumentType}";
            var request  = await CreateRequestAsync(resource, Method.PUT, cancellationToken).ConfigureAwait(false);

            request.AddFile(model.FileName, model.FileBytes, model.FileName);
            request.AlwaysMultipartFormData = true;
            return((await Client.ExecuteAsync <ApiResult <bool> >(request, cancellationToken).ConfigureAwait(false)).Data);
        }
Beispiel #7
0
        public void UploadWithWrongFileName_ExceptionThrown()
        {
            // Act
            var model = new AttachmentUploadModel
            {
                FileName = "Wr<>ng“F|leNam?.docx"
            };

            TestDelegate action = () => _attachmentClient.Upload(model).AssertResult();

            // Assert
            Assert.That(action, Throws.Exception.TypeOf <ValidationException>()
                        .And.Message.EqualTo("File name contains one or more unsupported characters"));
        }
        public async Task <IResultModel <AttachmentUploadResultModel> > Upload(AttachmentUploadModel model, FileInfo fileInfo)
        {
            var result = new ResultModel <AttachmentUploadResultModel>();
            var entity = new AttachmentEntity
            {
                Module   = model.Module,
                Group    = model.Group,
                FileName = model.Name.NotNull() ? model.Name : fileInfo.FileName,
                SaveName = fileInfo.SaveName,
                Ext      = fileInfo.Ext,
                Md5      = fileInfo.Md5,
                Path     = fileInfo.Path,
                FullPath = Path.Combine(fileInfo.Path, fileInfo.SaveName),
                Size     = fileInfo.Size.Size,
                SizeCn   = fileInfo.Size.ToString()
            };

            var mediaType = await _mediaTypeRepository.GetByExt(fileInfo.Ext);

            if (mediaType != null)
            {
                entity.MediaType = mediaType.Value;
            }

            using (var uow = _dbContext.NewUnitOfWork())
            {
                if (await _repository.AddAsync(entity))
                {
                    //如果需要授权访问附件,需要添加拥有者关联信息
                    var ownerEntity = new AttachmentOwnerEntity
                    {
                        AttachmentId = entity.Id,
                        AccountId    = model.AccountId
                    };
                    if (!model.Auth || await _ownerRepository.AddAsync(ownerEntity, uow))
                    {
                        uow.Commit();

                        var resultModel = _mapper.Map <AttachmentUploadResultModel>(entity);

                        return(result.Success(resultModel));
                    }
                }
            }

            return(result.Failed("上传失败"));
        }
Beispiel #9
0
        public void Upload_SuccessfullyUpdated()
        {
            // Arrange
            var model = new AttachmentUploadModel
            {
                FileBytes    = File.ReadAllBytes($"{TestContext.CurrentContext.TestDirectory}/{AttachmentPath}"),
                FileName     = FileName,
                DocumentType = AttachmentDocumentType.IssuedInvoice,
                DocumentId   = DocumentId
            };

            // Act
            var data = _attachmentClient.Upload(model).AssertResult();

            // Assert
            Assert.IsTrue(data);
        }
Beispiel #10
0
        /// <summary>
        /// Uploads attachment to document.
        /// </summary>
        /// <param name="model">File to upload.</param>
        /// <returns><see cref="ApiResult{TData}"/> instance containing <c>true</c> if upload of a document was successful, otherwise <c>false</c>.</returns>
        public ApiResult <bool> Upload(AttachmentUploadModel model)
        {
            if (model is null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (!IsAttachmentNameValid(model))
            {
                throw new ValidationException("File name contains one or more unsupported characters");
            }

            var resource = ResourceUrl + $"{model.DocumentId}/{model.DocumentType}";
            var request  = CreateRequest(resource, Method.PUT);

            request.AddFile(model.FileName, model.FileBytes, model.FileName);
            request.AlwaysMultipartFormData = true;
            return(Client.Execute <ApiResult <bool> >(request).Data);
        }
Beispiel #11
0
        public async Task <string> GetAttachmentFileID(string token, string userMail)
        {
            string fileID = string.Empty;

            Enforce.ArgumentNotNull <string>(token, "Token 不能为null");

            string key = string.Concat(prefix, token);

            string model = await this.database.StringGetAsync(key);

            //await this.database.KeyDeleteAsync(key);

            if (!string.IsNullOrEmpty(model))
            {
                AttachmentUploadModel attachmentUploadModel = Newtonsoft.Json.JsonConvert.DeserializeObject <AttachmentUploadModel>(model);

                if (attachmentUploadModel != null && attachmentUploadModel.userMail.Equals(userMail))
                {
                    fileID = attachmentUploadModel.fileID;
                }
            }

            return(fileID);
        }
Beispiel #12
0
        /**
         * This scenario demonstrates the creation of a document with Attachment.
         */
        public override async Task RunAsync()
        {
            // 1. The file's bytes must be read by the application and uploaded
            var filePath    = "sample.pdf";
            var fileName    = Path.GetFileName(filePath);
            var file        = File.ReadAllBytes(filePath);
            var uploadModel = await SignerClient.UploadFileAsync(fileName, file, "application/pdf");

            var fileUploadModel = new FileUploadModel(uploadModel)
            {
                DisplayName = "One Signer Sample"
            };


            // Repeat the same steps above but now for the attachment
            var attachmentPath   = "sample.pdf";
            var attachmentName   = Path.GetFileName(attachmentPath);
            var attachment       = File.ReadAllBytes(attachmentPath);
            var attachmentUpload = await SignerClient.UploadFileAsync(attachmentName, attachment, "application/pdf");

            // 2. Define the name of the attachment which will be visible in the application using "AttachmentUploadModel"
            var attachmentUploadModel = new AttachmentUploadModel(attachmentUpload)
            {
                DisplayName = "One Attachment Sample",
                IsPrivate   = true
            };


            // 3. For each participant on the flow, create one instance of ParticipantUserModel
            var participantUser = new ParticipantUserModel()
            {
                Name       = "Jack Bauer",
                Email      = "*****@*****.**",
                Identifier = "75502846369"
            };

            // 4. Create a FlowActionCreateModel instance for each action (signature or approval) in the flow.
            //    This object is responsible for defining the personal data of the participant and the type of
            //    action that he will perform on the flow
            var flowActionCreateModel = new FlowActionCreateModel()
            {
                Type = FlowActionType.Signer,
                User = participantUser
            };

            // 5. Send the document create request with whith the attachment attribute
            var documentRequest = new CreateDocumentRequest()
            {
                Files = new List <FileUploadModel>()
                {
                    fileUploadModel
                },
                Attachments = new List <AttachmentUploadModel>()
                {
                    attachmentUploadModel
                },
                FlowActions = new List <FlowActionCreateModel>()
                {
                    flowActionCreateModel
                }
            };
            var result = (await SignerClient.CreateDocumentAsync(documentRequest)).First();

            System.Console.WriteLine($"Document {result.DocumentId} created");
        }
Beispiel #13
0
        private bool IsAttachmentNameValid(AttachmentUploadModel attachment)
        {
            var unsupportedChars = new char[] { '\\', '/', '"', ':', '?', '*', '<', '>', '|', '“' };

            return(attachment.FileName.IndexOfAny(unsupportedChars) == -1);
        }
Beispiel #14
0
        public async Task <IResultModel> Upload(AttachmentUploadModel model, HttpRequest request)
        {
            var uploadModel = new FileUploadModel
            {
                Request  = request,
                FormFile = model.File,
                RootPath = _moduleCommonOptions.UploadPath,
                Module   = "Common",
                Group    = Path.Combine("Attachment", model.Module, model.Group)
            };

            //附件存储路径/Common/Attachment/{所属模块名称}/{所属分组模块}

            var result = await _fileUploadHelper.Upload(uploadModel);

            if (result.Successful)
            {
                var file   = result.Data;
                var entity = new AttachmentEntity
                {
                    Module   = model.Module,
                    Group    = model.Group,
                    FileName = file.FileName,
                    SaveName = file.SaveName,
                    Ext      = file.Ext,
                    Md5      = file.Md5,
                    Path     = file.Path,
                    FullPath = Path.Combine(file.Path, file.SaveName),
                    Size     = file.Size.Size,
                    SizeCn   = file.Size.ToString()
                };

                var mediaType = await _mediaTypeRepository.GetByExt(file.Ext);

                if (mediaType != null)
                {
                    entity.MediaType = mediaType.Value;
                }

                _uow.BeginTransaction();

                if (await _repository.AddAsync(entity))
                {
                    //如果需要授权访问附件,需要添加拥有者关联信息
                    if (!model.Auth || await _ownerRepository.AddAsync(new AttachmentOwnerEntity {
                        AttachmentId = entity.Id, AccountId = _loginInfo.AccountId
                    }))
                    {
                        _uow.Commit();

                        var resultModel = _mapper.Map <AttachmentUploadResultModel>(entity);
                        var url         = request.GetHost($"/common/attachment/download/{entity.Id}");
                        resultModel.Url = new Uri(url).ToString();

                        return(ResultModel.Success(resultModel));
                    }
                }
            }

            return(ResultModel.Failed("上传失败"));
        }
Beispiel #15
0
 public Task <IResultModel> Upload([FromForm] AttachmentUploadModel model)
 {
     return(_service.Upload(model, Request));
 }