コード例 #1
0
        public async void UploadFile(string filePath, UploadFileType uploadFileType, IUploadCallback uploadCallback)
        {
            FileStream fileStream = null;

            try
            {
                await Task.Run(() => { fileStream = File.Open(filePath, FileMode.Open); });

                var fileName = Path.GetFileName(filePath);

                var uploadTask = storageClient.Child(uploadFileType.ToString()).Child(fileName).PutAsync(fileStream);
                uploadTask.Progress.ProgressChanged += (s, e) => uploadCallback.SetUploadPercentage(e.Percentage);

                var downloadLink = await uploadTask;

                InsertUploadInfo(new UploadInfo {
                    Type = uploadFileType.ToString(), DownloadLink = downloadLink
                });

                uploadCallback.UploadCompleted();
            }
            catch (Exception ex)
            {
                uploadCallback.SetUploadPercentage(-1);
            }
        }
コード例 #2
0
        public async Task <Response> GetUploadInfos(UploadFileType uploadFileType)
        {
            try
            {
                var result = await client.Child("UploadInfo").OrderByKey().OnceAsync <UploadInfo>();

                var uploadInfos = new ObservableCollection <UploadInfo>();

                foreach (var item in result)
                {
                    var uploadInfo = item.Object as UploadInfo;
                    if (uploadInfo.Type == uploadFileType.ToString())
                    {
                        uploadInfos.Add(new UploadInfo {
                            DateTime = uploadInfo.DateTime, DownloadLink = uploadInfo.DownloadLink
                        });
                    }
                }

                return(new Response {
                    Success = true, UploadInfos = uploadInfos
                });
            }
            catch (Exception ex)
            {
                return(new Response {
                    Success = false
                });
            }
        }
コード例 #3
0
        public string UploadFile(string filename, UploadFileType fileType, int?timeout = null)
        {
            var query = FILTER_STR_HEADER + "*&UploadFileType=" + fileType.ToString();
            var path  = GenerateGetPath(HttpMethods.POST, query);

            return(WebClient.UploadFile(path, filename, timeout).ToString());
        }
コード例 #4
0
        private Dictionary <string, string> BuildQueryParamsUploadDoc(Guid projectId, UploadFileType uploadFileType,
                                                                      string filePath, Guid?folderId = null, string nameDocument                  = null, Guid?documentId = null,
                                                                      UploadTarget target            = UploadTarget.Document, UploadAction action = UploadAction.Add)
        {
            Dictionary <string, string> queryParams = new Dictionary <string, string>
            {
                { "file", uploadFileType.ToString().ToLowerInvariant() },
                { "action", action.ToString().ToLowerInvariant() },
                { "target", target.ToString().ToLowerInvariant() },
                { "projectid", projectId.ToString().ToLowerInvariant() }
            };

            if (target == UploadTarget.Document && action == UploadAction.Add)
            {
                if (String.IsNullOrEmpty(nameDocument) && !string.IsNullOrEmpty(filePath))
                {
                    nameDocument = Path.GetFileNameWithoutExtension(filePath);
                }
            }

            if (!String.IsNullOrEmpty(nameDocument))
            {
                queryParams.Add("name", nameDocument);
            }

            if (folderId.HasValue)
            {
                queryParams.Add("folderid", folderId.Value.ToString());
            }
            if (documentId.HasValue)
            {
                queryParams.Add("parentdocid", documentId.Value.ToString());
            }
            return(queryParams);
        }
コード例 #5
0
        /// <summary>
        /// <para>
        /// Uploads oversize content (template or policy) to S3.
        /// </para>
        /// This method will be called by create/update operations to upload oversize content to S3.
        /// <para></para>
        /// </summary>
        /// <param name="stackName">Name of the stack. Use to form part of the S3 key</param>
        /// <param name="body">String content to be uploaded.</param>
        /// <param name="originalFilename">File name of original input file, or <c>"RawString"</c> if the input was a string rather than a file</param>
        /// <param name="uploadFileType">Type of file (template or policy). Could be used to form part of the S3 key.</param>
        /// <returns>
        /// URI of uploaded template.
        /// </returns>
        public async Task <Uri> UploadOversizeArtifactToS3(
            string stackName,
            string body,
            string originalFilename,
            UploadFileType uploadFileType)
        {
            using (var ms = new MemoryStream(
                       new UTF8Encoding().GetBytes(body ?? throw new ArgumentNullException(nameof(body)))))
            {
                var bucket = await this.GetCloudFormationBucketAsync();

                var key = uploadFileType == UploadFileType.Template
                              ? this.timestampGenerator.GenerateTimestamp()
                          + $"_{stackName}_template_{originalFilename}"
                              : this.timestampGenerator.GenerateTimestamp() + $"_{stackName}_policy_{originalFilename}";

                var ub = new UriBuilder(bucket.BucketUri)
                {
                    Path = $"/{key}"
                };

                this.logger.LogInformation($"Copying oversize {uploadFileType.ToString().ToLower()} to {ub.Uri}");

                await this.s3.PutObjectAsync(
                    new PutObjectRequest
                {
                    BucketName      = this.cloudFormationBucket.BucketName,
                    Key             = key,
                    AutoCloseStream = true,
                    InputStream     = ms
                });

                return(ub.Uri);
            }
        }
コード例 #6
0
        public InvoiceDocumentViewModel GetAllAspNetUsersImage(string userId, UploadFileType fileType)
        {
            List <Expression <Func <InvoiceDocumentMapping, bool> > > filterPredicates = new List <Expression <Func <InvoiceDocumentMapping, bool> > >();

            filterPredicates.Add(p => p.UserId == userId);
            filterPredicates.Add(p => p.FileType == fileType.ToString());

            return(EntityToViewModelMapper.MapImage(this.InvoiceDocumentRepository.Find(filterPredicates)));
        }
コード例 #7
0
        public async Task <IEnumerable <ClaimDocumentViewModel> > GetAllClaimDocuments(string userId, int claimId, UploadFileType fileType)
        {
            List <Expression <Func <ClaimDocumentMapping, bool> > > filterPredicates = new List <Expression <Func <ClaimDocumentMapping, bool> > >();

            filterPredicates.Add(p => p.ClaimId == claimId);
            filterPredicates.Add(p => p.FileType == fileType.ToString());

            return(EntityToViewModelMapper.Map(this.ClaimDocumentRepository.Find(filterPredicates)));
        }
コード例 #8
0
        /// <summary>
        /// 存放路径,存放数据库
        /// </summary>
        /// <returns></returns>
        public static string GetFileUpLoadPath(UploadFileType type = UploadFileType.File)
        {
            string dic = type.ToString() + "/";

            dic += DateTime.Today.Year + "/";
            dic += DateTime.Today.Month + "/";
            dic += DateTime.Today.Day + "/";

            return(dic);
        }
コード例 #9
0
ファイル: GapClient.cs プロジェクト: saiedkia/GapBotApi
        public async Task <PostResult> Upload(string filePath, string fileName, UploadFileType uploadFileType, string fileDescription = null)
        {
            MultipartFormDataContent multipart = new MultipartFormDataContent();
            FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

            multipart.Add(new StreamContent(stream), uploadFileType.ToString().ToLower(), fileName);
            if (fileDescription != null)
            {
                multipart.Add(new StringContent(fileDescription), "desc");
            }
            _client.DefaultRequestHeaders.Add("desc", fileDescription);

            HttpResponseMessage response = await _client.PostAsync(baseUrl + "upload", multipart);

            PostResult postResult = await GetResult(response);

            return(postResult);
        }
コード例 #10
0
        public async Task <ActionResult> UploadClaimFiles(int claimId, UploadFileType fileType, IEnumerable <HttpPostedFileBase> claimFiles)
        {
            try
            {
                if (claimFiles != null && claimFiles.Any())
                {
                    string[] allowedFileExtensions = ConfigurationManager.AppSettings.Get("AllowedFileExtension").Split(',');
                    string   fileUploadLocation    = ConfigurationManager.AppSettings.Get("ClaimFilesUploadLocation");

                    if (!string.IsNullOrWhiteSpace(fileUploadLocation))
                    {
                        fileUploadLocation = Server.MapPath(Path.Combine(fileUploadLocation, claimId.ToString()));

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

                        foreach (HttpPostedFileBase postedFile in claimFiles)
                        {
                            if (postedFile.ContentLength > 0 && allowedFileExtensions.Contains(Path.GetExtension(postedFile.FileName).ToLower()))
                            {
                                string uploadFileName = String.Format("{0}{1}", Guid.NewGuid(), Path.GetExtension(postedFile.FileName));
                                string filePath       = Path.Combine(fileUploadLocation, uploadFileName);

                                switch (fileType)
                                {
                                case UploadFileType.Document:
                                case UploadFileType.Image:
                                    ClaimDocumentViewModel documentViewModel = new ClaimDocumentViewModel
                                    {
                                        ClaimId         = claimId,
                                        FileType        = fileType.ToString(),
                                        FileName        = uploadFileName,
                                        FileLocation    = fileUploadLocation,
                                        FileDisplayName = postedFile.FileName,
                                        CreatedBy       = User.Identity.GetUserId(),
                                        CreatedOn       = DateTime.Now,
                                        LastModifiedBy  = User.Identity.GetUserId(),
                                        LastModifiedOn  = DateTime.Now,
                                        IsActive        = true
                                    };
                                    documentViewModel = await ClaimDocumentBusinessLayer.Create(documentViewModel);

                                    if (documentViewModel.DocumentId > 0)
                                    {
                                        postedFile.SaveAs(filePath);
                                    }
                                    break;

                                default:
                                    break;
                                }
                            }
                        }
                    }

                    return(Content(""));
                }
            }
            catch (Exception ex)
            {
                this.ExceptionLogger.Log(LogLevel.Error, ex);
                throw ex;
            }

            return(null);
        }