public string Post([FromForm] FileUploads objectFile)
 {
     try
     {
         if (objectFile.files.Length > 0)
         {
             string path = _webHostEnvironment.WebRootPath + "\\Images\\";
             if (!Directory.Exists(path))
             {
                 Directory.CreateDirectory(path);
             }
             using (FileStream fileStream = System.IO.File.Create(path + objectFile.files.FileName))
             {
                 objectFile.files.CopyTo(fileStream);
                 fileStream.Flush();
                 return("Yüklendi.");
             }
         }
         else
         {
             return("Yüklenmedi");
         }
     }
     catch (Exception ex)
     {
         return(ex.Message);
     }
 }
Esempio n. 2
0
        public async Task <ActionResult> DeleteNews([FromRoute] int id)
        {
            try
            {
                var news = await _context.News.FindAsync(id);

                if (news == null)
                {
                    return(NotFound(new { Status = true, Msg = "Not found!!!" }));
                }

                var imagePaths = _context.ImageNews.Where(_ => _.NewsId == news.Id).ToList();
                if (imagePaths.Count > 0)
                {
                    _context.ImageNews.RemoveRange(imagePaths);
                    await _context.SaveChangesAsync();

                    FileUploads fileUploads = new FileUploads();
                    imagePaths.ForEach(path =>
                    {
                        fileUploads.DeleteImage(path.DirPath);
                    });
                }

                _context.News.Remove(news);
                await _context.SaveChangesAsync();

                return(Ok(new { Status = true, Msg = "Success" }));
            }
            catch (Exception ex)
            {
                return(Ok(new { Status = false, Msg = ex.Message }));
            }
        }
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }
            if (this.ProjectImage != null)
            {
                var ImageName    = FileUploads.GetFileName(this.ProjectImage.FileName);
                var uploadImages = Path.Combine(_hostEnvironment.WebRootPath, "ProjectImages");
                var imagePath    = Path.Combine(uploadImages, ImageName);
                this.ProjectImage.CopyTo(new FileStream(imagePath, FileMode.Create));
                this.Project.ProjectImage = ImageName; // Set the file name
            }
            if (this.ProjectScope != null)
            {
                var document        = FileUploads.GetFileName(this.ProjectScope.FileName);
                var documentsFolder = Path.Combine(_hostEnvironment.WebRootPath, "documents");
                var documentPath    = Path.Combine(documentsFolder, document);
                this.ProjectScope.CopyTo(new FileStream(documentPath, FileMode.Create));
                this.Project.ProjectScope = document; // Set the file name
            }
            _context.Project.Add(Project);
            await _context.SaveChangesAsync();

            return(RedirectToPage("./Index"));
        }
        //Return the control's current value
        //protected override object GetControlValue()
        //{
        //    return fileuploads;
        //}

        protected override void ReadEditModeValueCore()
        {
            if (PropertyValue != null)
            {
                fileuploads = (FileUploads)PropertyValue;
            }
            ASPxPanel upPanel = (ASPxPanel)Editor;

            //editorRender(ref upPanel);
        }
Esempio n. 5
0
        public async Task UploadFile(string filePath)
        {
            var fileUpload = new FileUpload()
            {
                FilePath = filePath
            };

            FileUploads.Add(fileUpload);
            await _fileTransferService.UploadFile(fileUpload, _viewer);
        }
Esempio n. 6
0
        //Return the control's current value
        //protected override object GetControlValue()
        //{
        //    return fileuploads;
        //}

        protected override void ReadEditModeValueCore()
        {
            if (CurrentObject != null)
            {
                fileuploads = CurrentObject as FileUploads;
            }
            ASPxPanel upPanel = (ASPxPanel)Editor;

            //editorRender(ref upPanel);
        }
Esempio n. 7
0
        protected string SaveFile(UploadedFile uploadedFile)
        {
            //IObjectSpace os = ((DevExpress.ExpressApp.DetailView)(View)).ObjectSpace;
            Session sess = (View.ObjectSpace as DevExpress.ExpressApp.Xpo.XPObjectSpace).Session;

            fileuploads = new FileUploads(sess);
            string appDir = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
            string appUrl = "./";

            if (uploadedFile.IsValid)
            {
                fileuploads.Name     = uploadedFile.FileName;
                fileuploads.FileName = uploadedFile.FileName;
                fileuploads.FileSize = uploadedFile.ContentLength;
                fileuploads.FileType = uploadedFile.ContentType; //PostedFile
                fileuploads.FileExt  = System.IO.Path.GetExtension(uploadedFile.FileName);

                string savePath;

                savePath  = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + @"Uploads\";
                savePath += CurrentObject.GetType().Name + @"\";
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(@savePath);
                }

                //Thêm số thứ tự vào tên file để tránh trùng lặp file
                if (File.Exists(string.Format("{0}{1}", savePath, fileuploads.FileName)))
                {
                    int    i           = 1;
                    string tmpFileName = string.Format("{0}.{1}{2}", fileuploads.FileName.Substring(0, fileuploads.FileName.Length - fileuploads.FileExt.Length), i, fileuploads.FileExt);
                    while (File.Exists(string.Format("{0}{1}", savePath, tmpFileName)))
                    {
                        i++;
                        tmpFileName = string.Format("{0}.{1}{2}", fileuploads.FileName.Substring(0, fileuploads.FileName.Length - fileuploads.FileExt.Length), i, fileuploads.FileExt);
                    }
                    fileuploads.FileName = tmpFileName;
                    //File.Delete(string.Format("{0}{1}", savePath, fileuploads.FileName));
                }

                uploadedFile.SaveAs(string.Format("{0}{1}", savePath, fileuploads.FileName)); //uncomment this line
                fileuploads.FileRealPath = savePath;
                if (HttpContext.Current != null)
                {
                    appUrl = HttpContext.Current.Request.Url.Authority;
                }
                fileuploads.FileUrl = string.Format("{0}\\{1}{2}", appUrl, fileuploads.FileRealPath.Replace(appDir, ""), fileuploads.FileName);
                fileuploads.Save();
                (CurrentObject as FleAttachments).FileAttachments.Add(fileuploads);
                (CurrentObject as FleAttachments).Save();
                //sess.CommitTransaction();
                //fileuploads.Session.CommitTransaction();
            }
            return(fileuploads.Name);
        }
        public FileContentResult DownloadFile()
        {
            int    fileId           = Convert.ToInt32(Request["fileId"]);
            string fileDownloadName = Request["fileDownloadName"];

            FileContentResult result = FileUploads.RetrieveFile(formsRepo, fileId);

            if (fileDownloadName != null)
            {
                result.FileDownloadName = fileDownloadName;
            }

            return(result);
        }
Esempio n. 9
0
        //public FileUploadsViewModel FileUploadProcess()
        //{
        //    var model = new FileUploadsViewModel();
        //    return model;
        //}

        public void FileUploadProcess(FileUploadsViewModel model)
        {
            FileUploads fileUpload = new FileUploads();
            var         repo       = new FileUplodRepository();

            byte[] uploadFile = new byte[model.File.InputStream.Length];

            model.File.InputStream.Read(uploadFile, 0, uploadFile.Length);

            fileUpload.FileName = model.File.FileName;
            fileUpload.File     = uploadFile;

            repo.Insert(fileUpload);
        }
        public void Update(FileUploads model)
        {
            var std = GetById(model.Id);

            //std.StudentName = model.StudentName;
            //std.Surname = model.Surname;
            //std.Initials = model.Initials;
            //std.StudentNumber = model.StudentNumber;
            //std.Surname = model.Surname;
            //std.email = model.email;
            //std.Contact = model.Contact;
            //std.GroupId = model.GroupId;
            //std.Address = model.Address;
            //_dbContext.Entry(std).State = System.Data.Entity.EntityState.Modified;
            _repository.Update(std);
        }
 protected override void SetupControl(WebControl control)
 {
     base.SetupControl(control);
     if (control.GetType().Name == "ASPxPanel") //ASPxUploadControl
     {
         if (PropertyValue != null)             //ViewEditMode == ViewEditMode.Edit &&
         {
             fileuploads = (FileUploads)PropertyValue;
             //Khu vực khác
             //if (fileuploads != null && control.GetType() == typeof(ASPxUploadControl))
             //{
             //    ((ASPxUploadControl)control).NullText = fileuploads.Name;
             //}
         }
     }
 }
Esempio n. 12
0
        private string findMagi(int index, int RelatedEnumId, int AttachTypeId)
        {
            string attachedForm = "";
            Dictionary <int, string> magiAttached = FileUploads.RetrieveFileDisplayTextsByRelatedId(formsRepo, SessionHelper.SessionForm.formResultId, RelatedEnumId, "A", AttachTypeId);

            foreach (var k in magiAttached.Keys)
            {
                string[] magi = magiAttached[k].Split('/');
                if (Convert.ToInt32(magi[0]) == index)
                {
                    attachedForm = magi[1];
                }
            }

            return(attachedForm);
        }
        private ASPxPanel editorSetup()
        {
            ASPxPanel editorPanel = new ASPxPanel();

            editorPanel.Width = Unit.Percentage(100);
            ASPxUploadControl upPanel = new ASPxUploadControl();

            upPanel.ID             = "upPanel";
            upPanel.FileUploadMode = UploadControlFileUploadMode.OnPageLoad;
            upPanel.ViewStateMode  = System.Web.UI.ViewStateMode.Enabled;
            upPanel.UploadMode     = UploadControlUploadMode.Auto; //Standard
            //upPanel.AddUploadButtonsHorizontalPosition = AddUploadButtonsHorizontalPosition.InputRightSide;
            upPanel.ShowProgressPanel = true;
            //upPanel.ShowAddRemoveButtons = true;
            upPanel.ProgressBarSettings.DisplayMode          = DevExpress.Web.ProgressBarDisplayMode.Percentage;
            upPanel.ValidationSettings.AllowedFileExtensions = new string[] { ".jpg", ".png", ".psd", ".pdf", ".gif", ".docx", ".doc",
                                                                              ".xls", ".xlsx", ".txt", ".zip", ".rar", ".fla", ".swf" };
            upPanel.ShowUploadButton               = true;
            upPanel.UploadButton.Image.Url         = "Images/upload.png";
            upPanel.UploadButton.Image.UrlDisabled = "Images/upload_disable.png";
            upPanel.UploadButton.ImagePosition     = DevExpress.Web.ImagePosition.Left;
            if (PropertyValue != null && PropertyValue.GetType() == typeof(FileUploads))
            {
                fileuploads = (FileUploads)PropertyValue;
            }
            upPanel.NullText = fileuploads == null ? "Click để chọn file upload.." : string.Format("{0}", fileuploads.Name);
            //upPanel.NullText = string.Format("File hiện tại: {0}", fileuploads == null ? "N/A" : fileuploads.Name);
            //Cho phep chon & upload nhieu file
            upPanel.AdvancedModeSettings.EnableMultiSelect = false;

            upPanel.FileUploadComplete += new EventHandler <FileUploadCompleteEventArgs>(uploadPanel_FileUploadComplete);
            //upPanel.PreRender
            //upPanel.CustomJSProperties

            ASPxLabel label   = new ASPxLabel();
            ASPxLabel lblNote = new ASPxLabel();

            lblNote.Text      = "Các bước UPLOAD file: \n1.Bấm 'Browse..' để chọn file.\n2. Bấm 'Upload' để tải file lên.\n3. Bấm 'Lưu' để xác nhận, file sẽ được lưu lên máy chủ.";
            lblNote.ForeColor = System.Drawing.Color.Gray;
            lblNote.BackColor = System.Drawing.Color.FromArgb(0xF2, 0xF2, 0xF2);
            label.ID          = "upLabelPanel";

            editorPanel.Controls.Add(label);
            editorPanel.Controls.Add(upPanel);
            editorPanel.Controls.Add(lblNote);
            return(editorPanel);
        }
        public bool UploadFile(FormCollection formCollection)
        {
            bool edit       = UAS_Business_Functions.hasPermission(UAS.Business.PermissionConstants.EDIT, UAS.Business.PermissionConstants.ASSMNTS);
            bool editlocked = UAS_Business_Functions.hasPermission(UAS.Business.PermissionConstants.EDIT_LOCKED, UAS.Business.PermissionConstants.ASSMNTS);
            int  fileId     = -1;

            if (edit || editlocked)
            {
                int RelatedEnumId = formsRepo.GetRelatedEnumIdByEnumDescription("formResultId");
                int AttachTypeId  = formsRepo.GetAttachTypeIdByAttachDescription("Generic Upload");

                int formResultId = Convert.ToInt32(formCollection["formResultId"]);
                System.Web.HttpPostedFileWrapper file = (System.Web.HttpPostedFileWrapper)Request.Files["file" + formResultId.ToString()];
                def_FormResults fr = formsRepo.GetFormResultById(formResultId);

                DateTime now    = DateTime.Now;
                string   date   = now.Year.ToString() + ((now.Month < 10) ? "0" : "") + now.Month.ToString() + ((now.Day < 10) ? "0" : "") + now.Day.ToString();
                string   time   = ((now.Hour < 10) ? "0" : "") + now.Hour.ToString() + ((now.Minute < 10) ? "0" : "") + now.Minute.ToString() + ((now.Second < 10) ? "0" : "") + now.Second.ToString();
                string   subDir = date + Path.DirectorySeparatorChar + time;

                fileId = FileUploads.CreateAttachment(formsRepo, file, null, subDir, formResultId, RelatedEnumId, AttachTypeId);

                // check if the file uploaded has a duplicated displayText for this assessment.  i.e., a logical overwrite.
                if (fileId > -1)
                {
                    def_FileAttachment       fa    = formsRepo.GetFileAttachment(fileId);
                    Dictionary <int, string> texts = FileUploads.RetrieveFileDisplayTextsByRelatedId(formsRepo, formResultId, RelatedEnumId, "A", AttachTypeId);

                    foreach (int k in texts.Keys)
                    {
                        if (texts[k].Equals(fa.displayText) && k != fa.FileId)
                        {
                            FileUploads.DeleteFile(formsRepo, k);
                        }
                    }
                }
            }

            if (fileId > -1)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Esempio n. 15
0
        public async Task UploadFile(string filePath)
        {
            var fileUpload = new FileUpload()
            {
                FilePath = filePath
            };

            App.Current.Dispatcher.Invoke(() =>
            {
                FileUploads.Add(fileUpload);
            });

            await _fileTransferService.UploadFile(fileUpload, _viewer, (double progress) =>
            {
                App.Current.Dispatcher.Invoke(() => fileUpload.PercentProgress = progress);
            });
        }
Esempio n. 16
0
        public ActionResult RetrieveMagi(int index)
        {
            //Use the index and the current formResultId to pull the fileAttachment record to find the formResultId of the MAGI form.
            int fileId        = -1;
            int RelatedEnumId = formsRepo.GetRelatedEnumIdByEnumDescription("formResultId");
            int AttachTypeId  = formsRepo.GetAttachTypeIdByAttachDescription("Def Form");

            string attachedForm = findMagi(index, RelatedEnumId, AttachTypeId);

            if (String.IsNullOrEmpty(attachedForm))
            {
                def_FormResults fr = formsRepo.GetFormResultById(SessionHelper.SessionForm.formResultId);

                def_FormResults magi = CreateMagiForm(fr.subject);
                attachedForm = magi.formResultId.ToString();

                def_FileAttachment fa = new def_FileAttachment()
                {
                    EnterpriseId  = SessionHelper.LoginStatus.EnterpriseID,
                    GroupId       = SessionHelper.LoginStatus.GroupID,
                    UserId        = fr.subject,
                    AttachTypeId  = AttachTypeId,
                    RelatedId     = fr.formResultId,
                    RelatedEnumId = RelatedEnumId,
                    displayText   = index + "/" + attachedForm,
                    FilePath      = index + "/" + attachedForm,
                    FileName      = attachedForm,
                    StatusFlag    = "A",
                    CreatedDate   = DateTime.Now,
                    CreatedBy     = SessionHelper.LoginStatus.UserID
                };
                FileUploads.CreateDataAttachment(formsRepo, SessionHelper.SessionForm.formResultId, fa);
            }

            // Save the current form data as a session variable
            SessionForm sf = new SessionForm();

            sf.formId       = SessionHelper.SessionForm.formId;
            sf.formResultId = SessionHelper.SessionForm.formResultId;
            sf.partId       = SessionHelper.SessionForm.partId;
            sf.sectionId    = SessionHelper.SessionForm.sectionId;
            sf.itemId       = SessionHelper.SessionForm.itemId;
            Session.Add("ParentFormData", sf);

            return(RedirectToAction("ToTemplate", "Adap", new { formResultId = attachedForm }));
        }
        public void DeleteFile()
        {
            bool edit       = UAS_Business_Functions.hasPermission(UAS.Business.PermissionConstants.EDIT, UAS.Business.PermissionConstants.ASSMNTS);
            bool editlocked = UAS_Business_Functions.hasPermission(UAS.Business.PermissionConstants.EDIT_LOCKED, UAS.Business.PermissionConstants.ASSMNTS);

            if (edit || editlocked)
            {
                int RelatedEnumId = formsRepo.GetRelatedEnumIdByEnumDescription("formResultId");

                int             formResultId = Convert.ToInt32(Request["formResultId"]);
                int             fileId       = Convert.ToInt32(Request["fileId"]);
                def_FormResults fr           = formsRepo.GetFormResultById(formResultId);

                if (!fr.locked || (fr.locked && editlocked))
                {
                    bool result = FileUploads.DeleteFile(formsRepo, fileId);
                }
            }
        }
Esempio n. 18
0
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }
            if (this.ProjectImage != null)
            {
                var ImageName    = FileUploads.GetFileName(this.ProjectImage.FileName);
                var uploadImages = Path.Combine(_hostEnvironment.WebRootPath, "ProjectImages");
                var imagePath    = Path.Combine(uploadImages, ImageName);
                this.ProjectImage.CopyTo(new FileStream(imagePath, FileMode.Create));
                this.Project.ProjectImage = ImageName; // Set the file name
            }
            if (this.ProjectScope != null)
            {
                var document        = FileUploads.GetFileName(this.ProjectScope.FileName);
                var documentsFolder = Path.Combine(_hostEnvironment.WebRootPath, "documents");
                var documentPath    = Path.Combine(documentsFolder, document);
                this.ProjectScope.CopyTo(new FileStream(documentPath, FileMode.Create));
                this.Project.ProjectScope = document; // Set the file name
            }

            _context.Attach(Project).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProjectExists(Project.ProjectID))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(RedirectToPage("./Index"));
        }
        private void viewRender(ref ASPxPanel viewPanel)
        {
            //ASPxPanel viewPanel = new ASPxPanel();
            ASPxHyperLink link    = RenderHelper.CreateASPxHyperLink(); // new ASPxHyperLink();
            ASPxLabel     lblSize = new ASPxLabel();
            ASPxLabel     lblType = new ASPxLabel();
            //iframe: PDF
            LiteralControl iframeShow = new LiteralControl();;

            if (PropertyValue != null) // && View != null
            {
                FileUploads file = (FileUploads)PropertyValue;
                //DetailView view = (DetailView)View;
                //System.Web.UI.WebControls.Panel layoutControl = ((System.Web.UI.WebControls.Panel)(view.Control));
                link.Width       = Unit.Pixel(200);
                link.BackColor   = System.Drawing.Color.AliceBlue;
                link.Text        = ((FileUploads)PropertyValue).Name;
                link.NavigateUrl = GetResolvedUrl(file.FileUrl);
                link.Target      = "_blank";

                lblSize.Text      = this.convertByte((int)file.FileSize);
                lblSize.Font.Bold = true;

                lblType.Text      = string.Format(" ({0})", file.FileType);
                lblType.ForeColor = System.Drawing.Color.DarkGray;

                iframeShow = new LiteralControl(string.Format("<iframe src=\"{0}\" style=\"width:100%; min-height:1200px;\"></iframe>", link.NavigateUrl));
            }


            viewPanel.Controls.Add(link);
            viewPanel.Controls.Add(lblSize);
            viewPanel.Controls.Add(lblType);
            viewPanel.Controls.Add(new LiteralControl("<p><br /></p>"));
            if (CurrentObject is DocumentFile)
            {
                viewPanel.Controls.Add(iframeShow);
            }

            //return viewPanel;
        }
        public string getFileDisplayText(int formResultId)
        {
            int RelatedEnumId = formsRepo.GetRelatedEnumIdByEnumDescription("formResultId");
            int AttachTypeId  = formsRepo.GetAttachTypeIdByAttachDescription("Generic Upload");
            Dictionary <int, string> displayTexts = FileUploads.RetrieveDistinctFileDisplayTextsByRelatedId(formsRepo, formResultId, RelatedEnumId, "A", AttachTypeId);
            string optionList = String.Empty;

            if (displayTexts.Count > 0)
            {
                optionList = "<select class=\"filesDDL" + formResultId + "\" style=\"min-width:100px\">";
                foreach (int key in displayTexts.Keys)
                {
                    optionList += "<option value=\"" + key + "\">" + displayTexts[key] + "</option>";
                }
                optionList += "</select>";
            }
            else
            {
                optionList = "<label style=\"min-width:100px\">No records found.</label>";
            }

            return(optionList);
        }
        public bool UploadCheck(FormCollection formCollection)
        {
            bool newFile       = true;
            int  RelatedEnumId = formsRepo.GetRelatedEnumIdByEnumDescription("formResultId");
            int  AttachTypeId  = formsRepo.GetAttachTypeIdByAttachDescription("Generic Upload");

            string data         = Request["arrayData"];
            int    formResultId = Convert.ToInt32(formCollection["formResultId"]);

            System.Web.HttpPostedFileWrapper file = (System.Web.HttpPostedFileWrapper)Request.Files["file" + formResultId.ToString()];
            def_FormResults fr = formsRepo.GetFormResultById(formResultId);

            Dictionary <int, string> texts = FileUploads.RetrieveFileDisplayTextsByRelatedId(formsRepo, formResultId, RelatedEnumId, "A", AttachTypeId);

            foreach (int k in texts.Keys)
            {
                if (file.FileName.Equals(texts[k]))
                {
                    newFile = false;
                }
            }

            return(newFile);
        }
Esempio n. 22
0
 public IEnumerable <FileUploadInfo> GetFileUploadList(string key)
 {
     return(FileUploads.Where(x => x.FileKey == key));
 }
Esempio n. 23
0
        protected string SaveFile(UploadedFile uploadedFile)
        {
            //IObjectSpace os = ((DevExpress.ExpressApp.DetailView)(View)).ObjectSpace;
            Session sess = (View.ObjectSpace as DevExpress.ExpressApp.Xpo.XPObjectSpace).Session;

            fileuploads = new FileUploads(sess);
            string appDir = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
            string appUrl = "./";

            if (uploadedFile.IsValid)
            {
                //fileName = string.Format("{0}{1}", MapPath("~/"), uploadedFile.FileName);
                fileuploads.Name     = uploadedFile.FileName;
                fileuploads.FileName = uploadedFile.FileName;
                fileuploads.FileSize = uploadedFile.ContentLength;
                fileuploads.FileType = uploadedFile.ContentType; //PostedFile
                fileuploads.FileExt  = System.IO.Path.GetExtension(uploadedFile.FileName);

                if (Global.Config == null)
                {
                    Global.Config = Configuration.GetInstance(this.View.ObjectSpace);
                }
                string savePath;// = string.Format("{0}/{1}", appDir, Global.Config.UploadPath);
                //string saveUrl = appUrl + "/" + Global.Config.UploadPath;

                savePath = fileuploads.newFullPathRender(fileuploads.FileName, View.CurrentObject != null ? View.CurrentObject.GetType().Name : "");
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(@savePath);
                }

                //Thêm số thứ tự vào tên file để tránh trùng lặp file
                if (File.Exists(string.Format("{0}{1}", savePath, fileuploads.FileName)))
                {
                    int    i           = 1;
                    string tmpFileName = string.Format("{0}.{1}{2}", fileuploads.FileName.Substring(0, fileuploads.FileName.Length - fileuploads.FileExt.Length), i, fileuploads.FileExt);
                    while (File.Exists(string.Format("{0}{1}", savePath, tmpFileName)))
                    {
                        i++;
                        tmpFileName = string.Format("{0}.{1}{2}", fileuploads.FileName.Substring(0, fileuploads.FileName.Length - fileuploads.FileExt.Length), i, fileuploads.FileExt);
                    }
                    fileuploads.FileName = tmpFileName;
                    //File.Delete(string.Format("{0}{1}", savePath, fileuploads.FileName));
                }

                uploadedFile.SaveAs(string.Format("{0}{1}", savePath, fileuploads.FileName)); //uncomment this line
                //fileuploads.FileRealPath = savePath;
                if (HttpContext.Current != null)
                {
                    appUrl = HttpContext.Current.Request.Url.Authority;
                }
                fileuploads.FileUrl = string.Format("{0}{1}{2}", appUrl, fileuploads.FileRealPath.Replace(appDir, ""), fileuploads.FileName);
                fileuploads.Save();
                if (CurrentObject is Document)
                {
                    DocumentFile docFile = new DocumentFile(sess);
                    docFile.DocFile        = fileuploads;
                    docFile.Document       = View.CurrentObject as Document;
                    docFile.UploadComplete = true;
                    docFile.Save();
                    current.FileAttachments.Add(docFile);
                }
                else if (CurrentObject is TaskExtra)
                {
                    TaskExtraFile taskFile = new TaskExtraFile(sess);
                    taskFile.UpFile         = fileuploads;
                    taskFile.TaskExtra      = View.CurrentObject as TaskExtra;
                    taskFile.UploadComplete = true;
                    taskFile.Save();
                    current.FileAttachments.Add(taskFile);
                }
                //sess.CommitTransaction();
                //fileuploads.Session.CommitTransaction();
            }
            return(fileuploads.Name);
        }
Esempio n. 24
0
 public byte[] fileData(FileUploads fileData)
 {
     return((byte[])fileData.File.ToArray());
 }
Esempio n. 25
0
        public async Task <IActionResult> UploadImage(FileUpload fileDetails)
        {
            IFormFile rawFile = fileDetails.UploadFile;

            if (fileDetails.UploadFile == null || fileDetails.UploadFile.Length == 0)
            {
                return(Content("file not selected"));
            }

            string filename = Guid.NewGuid().ToString() + rawFile.FileName;

            // var path = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot", rawFile.GetFilename());
            var imagePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/UploadedImages", filename);

            using (var stream = new FileStream(imagePath, FileMode.Create))
            {
                await rawFile.CopyToAsync(stream);
            }

            var          userId = Guid.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
            Organisation org;
            var          otheruser = _context.OtherUsers.Where(x => x.UserId == userId).FirstOrDefault();

            if (otheruser == null)
            {
                org = _context.Organisation.Where(m => m.ApplicationUserId == userId).FirstOrDefault();
            }
            else
            {
                org = _context.Organisation.Where(m => m.ApplicationUserId == otheruser.HostId).FirstOrDefault();
            }

            FileUploads newFile = new FileUploads()
            {
                OrganisationId = org.Id,
                FileName       = filename,
                Amount         = fileDetails.Amount,
                Description    = fileDetails.Description,
                UploadType     = "PAID INVOICE",
                Title          = fileDetails.Title,
                Id             = Guid.NewGuid()
            };

            _context.FileUpload.Add(newFile);
            _context.SaveChanges();

            var estm = _context.Estimates.Where(x => x.Id == fileDetails.Id).FirstOrDefault();

            estm.PaymentStatus = "PAID";

            _context.Update(estm);
            _context.SaveChanges();

            Transaction newTrans = new Transaction()
            {
                Id     = Guid.NewGuid(),
                Amount = estm.Total,
                TransactionDescription = "Payment Invoice " + estm.EstimateNo,
                TransactionType        = "Income",
                Tax            = 0,
                OrganisationId = org.Id
            };

            _context.Add(newTrans);
            _context.SaveChanges();



            //var estm = _context.Estimates.Where(x => x.Id == fileDetails.Id).FirstOrDefault();
            //estm.PaymentStatus = "PAID";

            //_context.Update(estm);
            //_context.SaveChanges();


            return(RedirectToAction(nameof(Index)));
        }
Esempio n. 26
0
 public string fileName(FileUploads fileRecord)
 {
     return(fileRecord.FileName);
 }
Esempio n. 27
0
        public FileUploads SearchFile(int?id)
        {
            FileUploads fileRecord = db.fileUpload.Find(id);

            return(fileRecord);
        }
Esempio n. 28
0
        public async Task <ActionResult> PostFileUploads([FromForm] FileUploadsCreate fileUploads) //[FromForm]
        {
            var    file = fileUploads.File;
            var    uploadResultImage = new ImageUploadResult();
            var    uploadResultRaw   = new RawUploadResult();
            string url;
            string publicId;

            if (file == null || file.Length == 0)
            {
                return(BadRequest("No file provided"));
            }

            if (file.Length > 400000)
            {
                return(BadRequest("File too big. Please resize it."));
            }

            using (var stream = file.OpenReadStream())
            {
                if (file.ContentType.Contains("image"))
                {
                    var uploadParamsImage = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream), // Name = "File", seems to work with images
                        Transformation = new Transformation().Width(400),        // this resizes the image maintaining the same aspect ratio
                    };
                    uploadResultImage = _cloudinary.Upload(uploadParamsImage);
                    if (uploadResultImage.Uri == null)
                    {
                        return(BadRequest("Could not upload file. Wrong file type."));
                    }
                    url      = uploadResultImage.Uri.ToString();
                    publicId = uploadResultImage.PublicId;
                }
                else
                {
                    var uploadParams = new RawUploadParams()
                    {
                        File = new FileDescription(file.FileName, stream), // Name = "File", FileName includes file name inc extension
                    };
                    uploadResultRaw = _cloudinary.Upload(uploadParams);
                    if (uploadResultRaw.Uri == null)
                    {
                        return(BadRequest("Could not upload file. Wrong file type."));
                    }
                    url      = uploadResultRaw.Uri.ToString();
                    publicId = uploadResultRaw.PublicId;
                }
            };

            var newFile = new FileUploads
            {
                URL         = url,
                CaseId      = fileUploads.CaseId,
                TimeStamp   = DateTime.Now,
                PublicId    = publicId,
                Description = fileUploads.Description
            };

            try
            {
                _context.FileUploads.Add(newFile);
                await _context.SaveChangesAsync();
            }
            catch
            {
                // error therefore should the uploaded file be deleted?
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }

            return(CreatedAtAction("GetFileUpload", new { id = newFile.Id }, newFile));
        }
Esempio n. 29
0
        private async Task DeleteOldPathImage(List <ImageGame> imagePaths, string fileName, FileUploads fileUploads)
        {
            //
            // delete old path
            if (imagePaths.Count > 0)
            {
                var descPath = imagePaths.Where(_ => _.Name == fileName).FirstOrDefault();
                if (descPath != null && !string.IsNullOrEmpty(descPath.DirPath))
                {
                    fileUploads.DeleteImage(descPath.DirPath);
                    _context.ImageGame.Remove(descPath);
                }

                await _context.SaveChangesAsync();
            }
        }
Esempio n. 30
0
        public async Task <bool> UploadImagesAsync([FromRoute] int id)
        {
            var files = Request.Form.Files;

            if (files.Count > 0)
            {
                var game = await _context.Game.FindAsync(id);

                if (game == null)
                {
                    throw new ApplicationException("Game is not existed");
                }

                var imageGames = await _context.ImageGame.Where(_ => _.GameId == id).ToListAsync();

                FileUploads fileUploads = new FileUploads();
                var         result      = new ImagePathsModel();

                foreach (var file in files)
                {
                    switch (file.Name)
                    {
                    case "banner":
                    {
                        result.PathBanner = fileUploads.UploadImage(file, "Banner_");

                        await DeleteOldPathImage(imageGames, file.Name, fileUploads);

                        await AddGameImage(file.Name, result.PathBanner, id);

                        break;
                    }

                    case "logo":
                    {
                        result.PathLogo = fileUploads.UploadImage(file, "Logo_");

                        await DeleteOldPathImage(imageGames, file.Name, fileUploads);

                        await AddGameImage(file.Name, result.PathLogo, id);

                        break;
                    }

                    default: break;
                    }

                    if (file.Name.Contains("description"))
                    {
                        var pathDesc = fileUploads.UploadImage(file, "Description_");
                        result.PathDescription.Add(pathDesc);

                        await DeleteOldPathImage(imageGames, file.Name, fileUploads);

                        await AddGameImage(file.Name, pathDesc, id);
                    }
                }

                if (!string.IsNullOrEmpty(result.PathBanner))
                {
                    game.Banner = result.PathBanner;
                }

                if (!string.IsNullOrEmpty(result.PathLogo))
                {
                    game.Logo = result.PathLogo;
                }

                for (int i = 0; i < result.PathDescription.Count; i++)
                {
                    game.Description = game.Description.Replace("{" + i + "}", "<img src=" + result.PathDescription[i] + " />");
                }

                await _context.SaveChangesAsync();
            }

            return(true);
        }