예제 #1
0
        public async Task <IActionResult> UploadSegmentFile()
        {   //==Form file Info ==
            var    formFile      = Request.Form.Files["file"];
            string correlationId = Request.Form["correlationId"];
            var    total         = Convert.ToInt32(Request.Form["totalCount"]);
            var    fileName      = Request.Form["fileName"];
            var    index         = Convert.ToInt32(Request.Form["index"]);
            string scopePath     = Request.Form["scopePath"];
            string category      = Request.Form["category"];

            var currentUserId        = HttpContext.CurrentUserId();
            var fileControlSetting   = _commonQueryService.GetFileControl();
            var newFileInfos         = new List <UploadFileResponseInfo>();
            FileResponseModel result = new FileResponseModel();

            logger.Info($"Begin to upload file. File count:{total}, current user:{HttpContext.CurrentUserName()}.");

            #region ==== Validate File Info =====
            if (index == 1)
            {
                UploadStatus validationResult = UploaderHelper.ValidationUploadFile(formFile.FileName, formFile.OpenReadStream(), fileControlSetting, true);
                if (validationResult != UploadStatus.ValidateSuccessful)
                {
                    logger.Warn($"Uploaded file is invalid. File name {formFile.Name}, size:{formFile.Length}, result:{validationResult}.");
                    return(Request.OK(new { msg = I18NEntity.GetString("GC_Common_Uploader_Failed_Message"), status = validationResult }));
                }
            }
            #endregion

            try
            {
                UploadFileRequestInfo info = new UploadFileRequestInfo()
                {
                    ScopePath     = !string.IsNullOrEmpty(scopePath) ? scopePath : ScopePath,
                    Category      = !string.IsNullOrEmpty(category) ? category : Category,
                    FileName      = fileName,
                    TotalCount    = total,
                    CorrelationId = !string.IsNullOrEmpty(correlationId) ? Guid.Parse(correlationId) : Guid.Empty,
                    Index         = index
                };

                if (total > 1)
                {
                    logger.Info($"Uploading Segment file {formFile.Name} to lcms.TotalCount:{info.TotalCount},current index:{info.Index}, CorrelationId:{info.CorrelationId}.");
                }
                else
                {
                    logger.Info($"Uploading file {formFile.Name} to lcms.");
                }

                UploadFileResponseInfo o = await _uploaderService.UploadFile(info, new Refit.StreamPart(formFile.OpenReadStream(), formFile.FileName));

                result.Info       = o;
                result.FileNumber = index;
                if (o.IsSucceed)
                {
                    //total file upload successfully
                    if (o.FileId != Guid.Empty)
                    {
                        logger.Info($"Uploading file {formFile.Name} to lcms succeed. File id:{o.FileId}.");
                        result.MergeResult = true;
                        o.Category         = Category;
                        result.ResponseFiles.Add(o);
                    }
                    else
                    {
                        result.MergeResult = false;
                    }
                }
                else
                {
                    logger.Warn($"Uploading file {formFile.Name} to lcms failed. File id:{o.FileId}, message:{o.ErrorMsg}.");
                    result.Msg = o.ErrorMsg;
                }
            }
            catch (TaskCanceledException ex)
            {
                logger.Error("Connection timed out and file upload failed. ", ex);
                return(Request.OK(new { msg = I18NEntity.GetString("GC_Common_Uploader_TimeOut_Message") }));
            }
            catch (ValidationException ex)
            {
                logger.Error("Validation file upload failed. ", ex);
                return(Request.OK(new { msg = I18NEntity.GetString("GC_Common_Uploader_Failed_Message"), ex.Status }));
            }
            catch (Exception ex)
            {
                logger.Error("Upload file to lcms server failed. ", ex);
            }

            return(Request.OK(result));
        }
예제 #2
0
        public async Task <MergeFileModel> FileMerge(string lastModified, string fileName)
        {
            MergeFileModel result = new MergeFileModel();

            try
            {
                var    temporary = Path.Combine(@"D:\tempFiles", lastModified);           //临时文件夹
                string fileExt   = Path.GetExtension(fileName);                           //获取文件后缀
                var    files     = Directory.GetFiles(temporary);                         //获得下面的所有文件
                var    finalPath = Path.Combine(@"D:\tempFiles", lastModified, fileName); //最终的文件名
                string scopePath = Request.Form["scopePath"];
                string category  = Request.Form["category"];

                UploadFileRequestInfo info = new UploadFileRequestInfo()
                {
                    ScopePath = !string.IsNullOrEmpty(scopePath) ? scopePath : ScopePath,
                    Category  = !string.IsNullOrEmpty(category) ? category : Category
                };

                UploadFileResponseInfo o;
                using (var fs = new FileStream(finalPath, FileMode.Create))
                {
                    foreach (var part in files.OrderBy(x => x.Length).ThenBy(x => x))//排一下序,保证从0-N Write
                    {
                        var bytes = System.IO.File.ReadAllBytes(part);
                        await fs.WriteAsync(bytes, 0, bytes.Length);

                        bytes = null;
                        System.IO.File.Delete(part);//删除分块
                    }
                    fs.Position = 0;
                    logger.Info($"Merge file successfully, {DateTime.Now} {fileName}, size {fs.Length}");

                    logger.Info($"Bengin send stream to lcsm, {DateTime.Now} {fileName}, size {fs.Length}");

                    o = await _uploaderService.UploadFile(info, new Refit.StreamPart(fs, fileName));

                    logger.Info($"End send stream to lcsm, {DateTime.Now} {fileName}");

                    result.MergeResult = true;
                }
                try
                {
                    if (System.IO.File.Exists(finalPath))
                    {
                        System.IO.File.Delete(finalPath);
                        logger.Info($"delete temp file successfully , {finalPath}");
                    }
                    if (Directory.Exists(temporary))
                    {
                        Directory.Delete(temporary);//删除文件夹
                        logger.Info($"delete temp folder successfully , {temporary}");
                    }
                }
                catch (Exception ex)
                {
                    logger.Error($"delete temp folder error : {ex.ToString()}");
                }

                if (o.IsSucceed)
                {
                    o.Category = Category;
                    result.ResponseFiles.Add(o);
                }
                else
                {
                    result.Msg  = o.ErrorMsg;
                    result.Info = o;
                }
            }
            catch (Exception ex)
            {
                logger.Error($"merge file error : {ex.ToString()}");
            }
            return(result);
        }