public IActionResult Post([FromForm] AddAttachmentDto dto
                                  , [FromServices] AddAttachmentValidator validator
                                  , [FromServices] IAddAttachmentCommand command)
        {
            var result = validator.Validate(dto);

            if (result.IsValid)
            {
                string fileName = CreateNewFileName(dto.File);

                string path = Path.Combine("wwwroot", "images", fileName);

                using (var fileStream = new FileStream(path, FileMode.Create))
                {
                    dto.File.CopyTo(fileStream);
                }

                //Save path, name, ticketId
                Attachment attachment = _mapper.Map <Attachment>(dto);
                attachment.Path = path;
                _useCaseExecutor.ExecuteCommand(command, attachment);

                return(Ok());
            }

            return(UnprocessableEntity(UnprocessableEntityResponse.Message(result.Errors)));
        }
Esempio n. 2
0
 private void Client_UploadProgressChanged(object sender, System.Net.UploadProgressChangedEventArgs e)
 {
     try
     {
         //Thread.Sleep(20);
         HttpWebClient <AddAttachmentDto> hbc = sender as HttpWebClient <AddAttachmentDto>;
         AddAttachmentDto dtos    = hbc.obj as AddAttachmentDto;
         AddAttachmentDto changed = _attachment.SingleOrDefault(m => m.fileGuid == (hbc.obj as AddAttachmentDto).fileGuid);
         if (e.ProgressPercentage != 100)
         {
             changed.btnStatus = e.ProgressPercentage + "%";
             if (changed.btnforeground != "2")
             {
                 changed.btnforeground = "2";
             }
         }
         else
         {
             changed.btnforeground = "0";
             changed.btnStatus     = "上传成功";
         }
         //Console.WriteLine(e.ProgressPercentage.ToString());
     }
     catch (Exception ex)
     {
         LogHelper.WriteError("[NoticeAddWindowViewModel_UploadProgressChanged]:" + ex.Message + ex.StackTrace + ex.Source);
     }
 }
 public void downMethodFile(AddAttachmentDto msg)
 {
     try
     {
         HttpWebClient <AddAttachmentDto> web = new HttpWebClient <AddAttachmentDto>();
         web.obj = msg;
         web.DownloadFileAsync(new Uri(msg.localPath), msg.path);
         web.DownloadProgressChanged += Web_DownloadProgressChanged;
         web.DownloadFileCompleted   += Web_DownloadFileCompleted;
     }
     catch (Exception ex)
     {
     }
 }
Esempio n. 4
0
        /// <summary>
        /// 上传接口2.0
        /// </summary>
        /// <param name="scid"></param>
        public void NoticeFileUpload(AddAttachmentDto scid)
        {
            try
            {
                //string url = ConfigurationManager.AppSettings["NewUpLoadAddress"];
                var    url  = AntSdkService.AntSdkConfigInfo.AntSdkFileUpload;
                string parm = string.Format("?&key={0}&requestTime={1}&File={2}&token={3}", 20000, (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000, "file", AntSdkService.AntSdkToken);
                HttpWebClient <AddAttachmentDto> client = new HttpWebClient <AddAttachmentDto>();
                client.Encoding = Encoding.UTF8;


                client.UploadProgressChanged += Client_UploadProgressChanged;;
                client.UploadFileCompleted   += Client_UploadFileCompleted;;
                client.UploadFileAsync(new Uri(url + parm), "POST", scid.localPath);
                client.obj = scid;
            }
            catch (Exception ex)
            {
                LogHelper.WriteError("[NoticeAddWindowViewModel_NoticeFileUpload]:" + ex.Message + ex.StackTrace);
            }
        }
        /// <summary>
        /// 下载进度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Web_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            HttpWebClient <AddAttachmentDto> hbc = sender as HttpWebClient <AddAttachmentDto>;
            AddAttachmentDto dtos  = hbc.obj as AddAttachmentDto;
            AddAttachmentDto downs = _attachment.SingleOrDefault(m => m.fileGuid == dtos.fileGuid);

            if (e.ProgressPercentage != 100)
            {
                downs.btnStatus = e.ProgressPercentage + "%";
                if (downs.btnforeground != "2")
                {
                    downs.btnforeground = "2";
                }
            }
            else
            {
                downs.downFileSucess = 1;
                downs.btnforeground  = "0";
                downs.btnStatus      = "查看";
            }
        }
Esempio n. 6
0
        private void Client_UploadFileCompleted(object sender, System.Net.UploadFileCompletedEventArgs e)
        {
            HttpWebClient <AddAttachmentDto> hbc = sender as HttpWebClient <AddAttachmentDto>;
            var str = Encoding.UTF8.GetString(e.Result);

            var dataStr      = string.Empty;
            var temperrorMsg = string.Empty;

            if (!GetValueByJsonKey("data", str, ref dataStr, ref temperrorMsg))
            {
                LogHelper.WriteError($"[NoticeAddWindowViewModel_NoticeFileUploadReturnError data is null]:{temperrorMsg}");
                return;
            }
            //处理
            var upoutput = JsonConvert.DeserializeObject <AntSdkFileUpLoadOutput>(dataStr);

            if (upoutput != null)
            {
                var fDto = new AddAttachmentDto
                {
                    data = new data
                    {
                        createTime  = upoutput.createTime,
                        downloadURL = upoutput.dowmnloadUrl,
                        fileMD5     = upoutput.fileMD5,
                        fileName    = upoutput.fileName,
                        fileSize    = upoutput.fileSize,
                        fileType    = upoutput.fileType
                    },
                    uploadFileSucess = 1
                };
                AddAttachmentDto changed =
                    _attachment.SingleOrDefault(m => m.fileGuid == (hbc.obj as AddAttachmentDto).fileGuid);

                changed.data             = fDto.data;
                changed.uploadFileSucess = 1;
                changed.btnforeground    = "0";
                changed.btnStatus        = "上传成功";
            }
        }
        public NoticeDetailsWindowViewModel(NoticeWindowListsViewModel notice, NoticeAddDto dtos)
        {
            this.notice = notice;
            this.dtos   = dtos;
            //inFindDetailsNotice inData = new inFindDetailsNotice();
            //inData.userId = AntSdkService.AntSdkCurrentUserInfo.userId;
            //inData.version = "1.0";
            //inData.notificationId = dtos.notificationId;
            //inData.token = AntSdkService.AntSdkLoginOutput.token;
            //ReturnNoticeAddDto rData = null;
            var    errorCode = 0;
            string errorMsg  = "";
            //TODO:AntSdk_Modify
            //DONE:AntSdk_Modify
            var result = AntSdkService.GetNotificationsById(dtos.notificationId, ref errorCode, ref errorMsg);

            //bool result = false;//new HttpService().SearchNoticeDetailsByNoticeId(inData, ref rData, ref errorMsg, GlobalVariable.RequestMethod.GET);
            if (result != null)
            {
                noticeTitle   = result.title;
                noticeContent = result.content;

                explain = result.createBy + "  编辑于  " + DataConverter.FormatTimeByTimeStamp(result.createTime);
                if (result.attach != null)
                {
                    gridHeight = 90;
                    List <data> datas = JsonConvert.DeserializeObject <List <data> >(result.attach);

                    foreach (var list in datas)
                    {
                        if (list == null)
                        {
                            continue;
                        }
                        AddAttachmentDto add = new AddAttachmentDto();
                        add.fileGuid = Guid.NewGuid().ToString().Replace("-", "");
                        add.fileName = list.fileName;
                        if (Convert.ToInt32(list.fileSize) < 1024)
                        {
                            add.fileLength = list.fileSize + "B";
                        }
                        if (Convert.ToInt32(list.fileSize) > 1024)
                        {
                            add.fileLength = Math.Round((double)Convert.ToInt32(list.fileSize) / 1024, 2) + "KB";
                        }
                        if (Convert.ToInt32(list.fileSize) > 1024 * 1024)
                        {
                            add.fileLength = Math.Round((double)Convert.ToInt32(list.fileSize) / 1024 / 1024, 2) + "MB";
                        }
                        add.localPath     = list.downloadURL;
                        add.fileimageShow = fileShowImage.showImageHtmlPath(list.fileType, "");
                        add.btnStatus     = "downLoad";
                        add.btnforeground = "0";
                        _attachment.Add(add);
                    }
                }
                else
                {
                    gridHeight = 0;
                }
            }
        }
        /// <summary>
        /// 下载完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Web_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            AddAttachmentDto changed = _attachment.SingleOrDefault(m => m.fileGuid == ((sender as HttpWebClient <AddAttachmentDto>).obj as AddAttachmentDto).fileGuid);

            changed.uploadFileSucess = 1;
        }
        public async Task <IActionResult> UploadAttachment([FromForm] AddAttachmentDto dto)
        {
            var userId = User.GetUserId();

            if (dto.Attachment != null)
            {
                var attachment = dto.Attachment;
                var folderName = Path.Combine("Resources", "Attachments", dto.IssueId);
                var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);

                var fileName = ContentDispositionHeaderValue.Parse(attachment.ContentDisposition).FileName.Trim('"');

                var fullPath = Path.Combine(pathToSave, fileName);

                while (System.IO.File.Exists(fullPath))
                {
                    var fileNameNoExt = fileName.Split('.')[0];
                    var ext           = fileName.Split('.')[1];

                    if (fileNameNoExt.Length > 8 &&
                        fileNameNoExt.Substring(fileNameNoExt.Length - 7, 4) == "Copy")
                    {
                        var copyNumber = int.Parse(fileNameNoExt[fileNameNoExt.Length - 2].ToString());
                        fileNameNoExt = $"{fileNameNoExt.Substring(0, fileNameNoExt.Length - 2)}{++copyNumber})";
                    }
                    else
                    {
                        fileNameNoExt += "(Copy-1)";
                    }

                    fileName = $"{fileNameNoExt}.{ext}";

                    fullPath = Path.Combine(pathToSave, fileName);
                }

                var dbPath = Path.Combine(folderName, fileName);

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

                using (var stream = new FileStream(fullPath, FileMode.Create))
                {
                    attachment.CopyTo(stream);
                }

                var newAttachment = new Attachment
                {
                    Url         = dbPath,
                    CreatedById = userId,
                    IssueId     = dto.IssueId,
                    Size        = Convert.ToInt32(attachment.Length)
                };

                _repo.Add(newAttachment);

                if (await _repo.SaveAll())
                {
                    newAttachment.CreatedBy = await _repo.GetUser(newAttachment.CreatedById);

                    var attachmentToReturn = _mapper.Map <AttachmentDto>(newAttachment);
                    return(Ok(attachmentToReturn));
                }

                return(BadRequest());
            }

            return(BadRequest());
        }