Ejemplo n.º 1
0
        //todo move out
        public async Task <string> UploadImageAsync(IFormFile image)
        {
            var ext = Path.GetExtension(image.FileName).ToLowerInvariant();

            if (string.IsNullOrEmpty(ext) || !Constants.permittedExtensions.Contains(ext))
            {
                return(null);
            }
            else

            {
                string fileName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0')
                                  + "_" + DateTime.Now.Hour.ToString().PadLeft(2, '0') + DateTime.Now.Minute.ToString().PadLeft(2, '0') + DateTime.Now.Second.ToString().PadLeft(2, '0')
                                  + "_" + DateTime.Now.Millisecond.ToString().PadLeft(4, '0') + ext;

                string filePath = GetFilePathUpdate(fileName);

                using (var stream = System.IO.File.Create(filePath))
                {
                    await image.CopyToAsync(stream);

                    UploadImageHelper.ResizeAndSaveImage(stream, GetThumbFilePathUpdate(fileName));
                }

                return(fileName);
            }
        }
Ejemplo n.º 2
0
        public async Task <string> UploadImageAsync(PostBindingModel postData)
        {
            var ext = Path.GetExtension(postData.ImageFile.FileName).ToLowerInvariant();

            if (string.IsNullOrEmpty(ext) || !Constants.permittedExtensions.Contains(ext))
            {
                return(null);
            }
            else

            {
                string fileName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0')
                                  + "_" + DateTime.Now.Hour.ToString().PadLeft(2, '0') + DateTime.Now.Minute.ToString().PadLeft(2, '0') + DateTime.Now.Second.ToString().PadLeft(2, '0')
                                  + "_" + DateTime.Now.Millisecond.ToString().PadLeft(4, '0') + ext;

                string filePath = Path.Combine(_configuration.GetValue <string>("CustomSettings:PostsUploadPath"), fileName);

                using (var stream = System.IO.File.Create(filePath))
                {
                    await postData.ImageFile.CopyToAsync(stream);

                    UploadImageHelper.ResizeAndSaveImage(stream, Path.Combine(_configuration.GetValue <string>("CustomSettings:PostsUploadPath"), "thumb", fileName));
                }

                return(fileName);
            }
        }
Ejemplo n.º 3
0
        public ActionResult EditarMenuItems(Menu model, HttpPostedFileBase IconoFile)
        {
            model.GruposMenu = DropDownListHelper.p_AEPSAD_MenuGrupos(model.MenuGrupoId);

            try
            {
                String _error = String.Empty;
                String _icono = String.Empty;

                bool _isFileUploaded = UploadImageHelper.p_AEPSAD_UploadImage(IconoFile, "IconoMenu_" + model.Id, ref _icono, ref _error);

                if (!_isFileUploaded)
                {
                    ModelState.AddModelError("IconoFile", _error);
                }

                if (!ModelState.IsValid)
                {
                    return(View(model));
                }

                MenuModel _m = new MenuModel
                {
                    Id           = model.Id,
                    MenuGrupoId  = model.MenuGrupoId,
                    Texto        = model.Texto,
                    Enlace       = model.Enlace,
                    Icono        = _icono,
                    NuevaVentana = (model.NuevaVentana ? Convert.ToByte(1) : Convert.ToByte(0)),
                    Orden        = model.Orden
                };


                HttpClient _client = WebApiHelper.p_APESAD_HttpClient(SessionHelper.p_AEPSAD_get_usuario().Token);


                var _json    = JsonConvert.SerializeObject(_m);
                var _content = new StringContent(_json.ToString(), Encoding.UTF8, "application/json");

                HttpResponseMessage _response = _client.PutAsync(WebApiHelper.ENDPOINT_MENU_UPDATE, _content).Result;

                if (_response.IsSuccessStatusCode)
                {
                    ViewBag.JavaScriptFunction = string.Format("p_AEPSAD_save_ok('Los datos han sido actualizados');");
                }
                else
                {
                    ErrorHelper.p_AEPSAD_Log(_response.ReasonPhrase);
                    ViewBag.JavaScriptFunction = string.Format("p_AEPSAD_error('" + _response.ReasonPhrase + "');");
                }

                return(View(model));
            }
            catch (Exception ex)
            {
                ErrorHelper.p_AEPSAD_Log(ex);
                ViewBag.JavaScriptFunction = string.Format("p_AEPSAD_error('" + ex.Message + "');");
                return(View(model));
            }
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> Edit(int Id, HomePageCoversEditBindingModel model)
        {
            if (Id != model.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                var image = _context.HomePageCovers.AsNoTracking().Where(i => i.Id == Id).FirstOrDefault();
                if (image == null)
                {
                    return(NotFound());
                }

                using (var stream = System.IO.File.Create(GetFilePathUpdate(model.UploadImage.FileName)))
                {
                    await model.UploadImage.CopyToAsync(stream);

                    UploadImageHelper.ResizeAndSaveImage(stream, GetThumbFilePathUpdate(model.UploadImage.FileName));
                }

                image.Title    = model.Title;
                image.FileName = model.UploadImage.FileName;
                _context.Update(image);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                return(View());
            }
        }
Ejemplo n.º 5
0
        public string Import(HttpContext context)//导入数据
        {
            UploadImageHelper uploadBll = new UploadImageHelper();
            HttpPostedFile    file      = context.Request.Files["Filedata"];
            string            fileName  = file.FileName;
            //string tempPath = AppDomain.CurrentDomain.BaseDirectory + "/UploadFile/" + "AppBox/";

            string tempPath = HttpContext.Current.Server.MapPath("~/UploadFile/AppBox/");

            //创建目录
            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }
            fileName = System.IO.Path.GetFileName(fileName);                  //获取文件名(不带路径)
            string currFileExtension = System.IO.Path.GetExtension(fileName); //获取文件的扩展名
            string currFilePath      = tempPath + fileName;                   //获取上传后的文件路径 记录到前面声明的全局变量

            file.SaveAs(currFilePath);
            try
            {
                //七牛
                string strName  = Guid.NewGuid().ToString("N") + ".png";
                bool   state    = uploadBll.UpLoadImage(currFilePath, out strName, true);
                string imageUrl = uploadBll.QiniuDomain + strName;
                return(imageUrl);
            }
            catch
            {
                return("false");
            }
        }
Ejemplo n.º 6
0
        public async Task <Request> Put(int requestId, EditRequestModel model)
        {
            var requestModel = GetQuery().Include("RequestDetails").Include("RequestDetails.FormField").FirstOrDefault(x => x.Id == requestId);

            if (requestModel == null)
            {
                throw new NotFoundException();
            }

            var request = _mapper.Map <Request>(requestModel);

            for (int i = 0; i < request.RequestDetails.Count; i++)
            {
                var newValue = model.RequestDetails.Where(a => a.Id == request.RequestDetails[i].Id).FirstOrDefault();

                if (newValue != null && newValue.FormFieldId == 10 && request.RequestDetails[i].Value != newValue.Value)
                {
                    model.RequestDetails[i].Value = UploadImageHelper.SaveImage(model.RequestDetails[i].Value, "Requests");
                }
                else if (newValue != null && newValue.FormFieldId == 8 && request.RequestDetails[i].Value != newValue.Value)
                {
                    model.RequestDetails[i].Value = UploadImageHelper.SavePdf(model.RequestDetails[i].Value, "Requests");
                }
                else
                {
                    request.RequestDetails[i].Value = newValue == null ? "" : newValue.Value;
                }
            }

            var deletedItems = request.RequestDetails.Where(a => !model.RequestDetails.Any(x => a.Id == x.Id)).Select(a => a.Id).ToArray();

            foreach (var item in deletedItems)
            {
                var reqDetail = request.RequestDetails.Where(a => a.Id == item).First();
                request.RequestDetails.Remove(reqDetail);
            }

            var addedItems = model.RequestDetails.Where(a => a.Id == 0);

            foreach (var item in addedItems)
            {
                request.RequestDetails.Add(new RequestDetail
                {
                    RequestId   = requestId,
                    FormFieldId = item.FormFieldId,
                    Value       = item.Value
                });
            }

            await _uow.CommitAsync();

            return(request);
        }
        public async Task <Bid> Put(int bidId, EditBidModel model)
        {
            var bidModel = GetQuery().Include("BidDetails").Include("BidDetails.FormField").FirstOrDefault(x => x.Id == bidId);

            if (bidModel == null)
            {
                throw new NotFoundException();
            }

            var bid = _mapper.Map <Bid>(bidModel);

            for (int i = 0; i < bid.BidDetails.Count; i++)
            {
                var newValue = model.BidDetails.Where(a => a.Id == bid.BidDetails[i].Id).FirstOrDefault();

                if (newValue != null && newValue.FormFieldId == 10 && bid.BidDetails[i].Value != newValue.Value)
                {
                    model.BidDetails[i].Value = UploadImageHelper.SaveImage(model.BidDetails[i].Value, "Bids");
                }
                else if (newValue != null && newValue.FormFieldId == 8 && bid.BidDetails[i].Value != newValue.Value)
                {
                    model.BidDetails[i].Value = UploadImageHelper.SavePdf(model.BidDetails[i].Value, "Bids");
                }
                else
                {
                    bid.BidDetails[i].Value = newValue == null ? "" : newValue.Value;
                }
            }

            var deletedItems = bid.BidDetails.Where(a => !model.BidDetails.Any(x => a.Id == x.Id)).Select(a => a.Id).ToArray();

            foreach (var item in deletedItems)
            {
                var reqDetail = bid.BidDetails.Where(a => a.Id == item).First();
                bid.BidDetails.Remove(reqDetail);
            }

            var addedItems = model.BidDetails.Where(a => a.Id == 0);

            foreach (var item in addedItems)
            {
                bid.BidDetails.Add(new  BidDetail
                {
                    BidId       = bidId,
                    FormFieldId = item.FormFieldId,
                    Value       = item.Value
                });
            }

            await _uow.CommitAsync();

            return(bid);
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> UploadCoverPhotos(HomePageCoversBindingModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (model.UploadImage.Length > 0)
                    {
                        var ext = Path.GetExtension(model.UploadImage.FileName).ToLowerInvariant();

                        if (string.IsNullOrEmpty(ext) || !Constants.permittedExtensions.Contains(ext))
                        {
                            ModelState.AddModelError("InvoiceFile", "Invalid File Type!");
                            return(View());//todo
                        }
                        else
                        {
                            string fileName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0')
                                              + "_" + DateTime.Now.Hour.ToString().PadLeft(2, '0') + DateTime.Now.Minute.ToString().PadLeft(2, '0') + DateTime.Now.Second.ToString().PadLeft(2, '0')
                                              + "_" + DateTime.Now.Millisecond.ToString().PadLeft(4, '0') + ext;

                            using (var stream = System.IO.File.Create(GetFilePathUpdate(fileName)))
                            {
                                await model.UploadImage.CopyToAsync(stream);

                                UploadImageHelper.ResizeAndSaveImage(stream, GetThumbFilePathUpdate(fileName));
                            }

                            HomePageCover image = new HomePageCover()
                            {
                                Title    = model.Title,
                                FileName = fileName
                            };

                            _context.HomePageCovers.Add(image);
                        }
                    }

                    _context.SaveChanges();
                    return(RedirectToAction("Index", "HomePageManagement"));
                }
                else
                {
                    return(View(model));
                }
            }

            catch
            {
                throw;
            }
        }
Ejemplo n.º 9
0
        private async Task OnTapped()
        {
            Image = await UploadImageHelper.UploadImage(Image);

            var request = new PlaylistUpsertRequest()
            {
                Name      = Playlist.Name,
                CreatedAt = Playlist.CreatedAt,
                UserID    = Playlist.UserID,
                Image     = Image
            };

            await _service.Update <Playlist>(Playlist.ID, request);
        }
Ejemplo n.º 10
0
 public ImageService(
     IImageRepository imageRepo,
     ICategoryRepository categoryRepo,
     IMapper mapper,
     IHostingEnvironment env,
     IConfiguration config,
     IOptions <AzureStorageConfig> azureStorageConfig,
     UploadImageHelper imageHelper)
 {
     _imageRepo          = imageRepo;
     _categoryRepo       = categoryRepo;
     _mapper             = mapper;
     _env                = env;
     _config             = config;
     _imageHelper        = imageHelper;
     _azureStorageConfig = azureStorageConfig.Value;
     _env                = env;
 }
Ejemplo n.º 11
0
        public async Task <UploadResult> UploadImage(IFormFileCollection files, AddImageViewModel vm)
        {
            var result = new UploadResult();

            foreach (var file in files)
            {
                if (UploadImageHelper.IsImage(file))
                {
                    vm.Name.Replace(' ', '_');
                    var fileName = $"{Guid.NewGuid()}{vm.Name}";

                    var fileStream = await UploadImageHelper.UploadImage(file, fileName, file.ContentType, _azureStorageConfig);

                    if (fileStream != null)
                    {
                        //try
                        //{
                        var client = new WebClient
                        {
                            Credentials = new NetworkCredential(CDNProfile.Username, CDNProfile.Password)
                        };
                        client.UploadFile(
                            "ftp://[email protected]/www/Picks",
                            WebRequestMethods.Ftp.AppendFile,
                            $"{fileStream.Name}");

                        var img = new Image()
                        {
                            CategoryId = vm.CategoryId,
                            Name       = vm.Name
                        };

                        await _imageRepo.Add(img);

                        //}
                        //catch (Exception err)
                        //{
                        //    return null;
                        //}
                    }
                }
            }
            return(result);
        }
        public async Task <Bid> Create(CreateBidModel model)
        {
            for (int i = 0; i < model.BidDetails.Count; i++)
            {
                if (model.BidDetails[i].FieldTypeId == 10)
                {
                    model.BidDetails[i].Value = UploadImageHelper.SaveImage(model.BidDetails[i].Value, "Bids");
                }
                else if (model.BidDetails[i].FieldTypeId == 8)
                {
                    model.BidDetails[i].Value = UploadImageHelper.SavePdf(model.BidDetails[i].Value, "Bids");
                }
            }

            var request = _mapper.Map <Bid>(model);

            _uow.Add(request);
            await _uow.CommitAsync();

            return(request);
        }
Ejemplo n.º 13
0
        public async Task <Request> Create(CreateRequestModel model)
        {
            for (int i = 0; i < model.RequestDetails.Count; i++)
            {
                if (model.RequestDetails[i].FieldTypeId == 10)
                {
                    model.RequestDetails[i].Value = UploadImageHelper.SaveImage(model.RequestDetails[i].Value, "Requests");
                }
                else if (model.RequestDetails[i].FieldTypeId == 8)
                {
                    model.RequestDetails[i].Value = UploadImageHelper.SavePdf(model.RequestDetails[i].Value, "Requests");
                }
            }

            var request = _mapper.Map <Request>(model);

            request.StatusId = (int)RequestStatus.Opened;
            _uow.Add(request);
            await _uow.CommitAsync();

            return(request);
        }
Ejemplo n.º 14
0
        private List <ImageDTO> ConvertFromBase64(List <ImageBase64Request> requests)
        {
            var images = new List <ImageDTO>();

            if (requests != null)
            {
                foreach (var request in requests)
                {
                    var url = UploadImageHelper.PostBase64Image(request);

                    images.Add(new ImageDTO()
                    {
                        OriginalImage = url.ElementAt(0),
                        ResizedImage  = url.ElementAt(1),
                    });
                }

                return(images);
            }

            return(images);
        }
Ejemplo n.º 15
0
        public ActionResult Save(Guid id, PhotoViewModel backModel, HttpPostedFileBase upload, IEnumerable <HttpPostedFileBase> uploads)
        {
            ErrorMessage message = new ErrorMessage
            {
                Title = "Информация"
            };

            if (ModelState.IsValid)
            {
                bool status = false;
                backModel.Item.Id = id;
                string path = $"{Settings.UserFiles}{SiteDir}{Settings.PhotoDir}{id}/";

                if (upload != null && upload.ContentLength > 0)
                {
                    if (!allowedExtention.Contains(upload.FileName.Substring(upload.FileName.LastIndexOf('.') + 1)))
                    {
                        model.ErrorInfo = new ErrorMessage()
                        {
                            Title   = "Ошибка",
                            Info    = "Вы не можете загружать файлы данного формата",
                            Buttons = new ErrorMessageBtnModel[]
                            {
                                new ErrorMessageBtnModel {
                                    Url = "#", Text = "ок", Action = "false", Style = "primary"
                                }
                            }
                        };
                        return(View("Item", model));
                    }
                    backModel.Item.Preview = SavePreviewAlbum(upload, path);
                }

                if (_cmsRepository.CheckPhotoAlbumExists(id))
                {
                    status       = _cmsRepository.UpdatePhotoAlbum(backModel.Item);
                    message.Info = "Запись обновлена";
                }
                else
                {
                    status       = _cmsRepository.InsertPhotoAlbum(backModel.Item);
                    message.Info = "Запись сохранена";
                }

                if (uploads != null && uploads.Any(a => a != null))
                {
                    var helper = new UploadImageHelper
                    {
                        Uploads       = uploads,
                        Path          = path,
                        AlbumId       = id,
                        IsNeedPreview = String.IsNullOrWhiteSpace(backModel.Item.Preview)
                    };
                    string prev = SaveUploadImages(helper);
                    if (!String.IsNullOrWhiteSpace(prev))
                    {
                        _cmsRepository.UpdatePhotoAlbumPreview(id, prev);
                    }
                }

                message.Buttons = new ErrorMessageBtnModel[]
                {
                    new ErrorMessageBtnModel {
                        Url = $"{StartUrl}{Request.Url.Query}", Text = "вернуться в список"
                    },
                    new ErrorMessageBtnModel {
                        Url = $"{StartUrl}item/{id}", Text = "ок", Action = "false"
                    }
                };
            }
            else
            {
                message.Info    = "Ошибка в заполнении формы. Поля, в которых допущены ошибки помечены цветом.";
                message.Buttons = new ErrorMessageBtnModel[]
                {
                    new ErrorMessageBtnModel {
                        Url = "#", Text = "ок", Action = "false"
                    }
                };
            }

            model.Item      = _cmsRepository.GetPhotoAlbum(id);
            model.ErrorInfo = message;
            return(View("item", model));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Сохраняет изображения для альбома
        /// </summary>
        /// <param name="uploads"></param>
        private string SaveUploadImages(UploadImageHelper helper)
        {
            int counter = 0;

            PhotoModel[] photoList    = new PhotoModel[helper.Uploads.Count()];
            string       albumPreview = null;

            foreach (var photo in helper.Uploads)
            {
                if (photo != null && photo.ContentLength > 0)
                {
                    if (allowedExtention.Contains(photo.FileName.Substring(photo.FileName.LastIndexOf('.') + 1)))
                    {
                        if (!Directory.Exists(Server.MapPath(helper.Path)))
                        {
                            Directory.CreateDirectory(Server.MapPath(helper.Path));
                        }
                        string newFilename = $"{(counter + 1).ToString()}.jpg";

                        //сохраняем оригинал
                        photo.SaveAs(Server.MapPath(Path.Combine(helper.Path, newFilename)));

                        ImageCodecInfo    myImageCodecInfo    = GetEncoderInfo("image/jpeg");
                        EncoderParameters myEncoderParameters = new EncoderParameters(1);
                        myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);

                        Bitmap _File = (Bitmap)Bitmap.FromStream(photo.InputStream);

                        //оригинал
                        Bitmap _FileOrigin = Imaging.Resize(_File, 4000, "width");
                        _FileOrigin.Save(Server.MapPath($"{helper.Path}{newFilename}"), myImageCodecInfo, myEncoderParameters);

                        //сохраняем full hd
                        Bitmap _FileHd = Imaging.Resize(_File, 2000, "width");
                        _FileHd.Save(Server.MapPath($"{helper.Path}hd_{newFilename}"), myImageCodecInfo, myEncoderParameters);

                        //сохраняем превью
                        Bitmap _FilePrev = Imaging.Resize(_File, 120, 120, "center", "center");
                        _FilePrev.Save(Server.MapPath($"{helper.Path}prev_{newFilename}"), myImageCodecInfo, myEncoderParameters);

                        if (helper.IsNeedPreview && counter == 0)
                        {
                            albumPreview = SavePreviewAlbum(photo, helper.Path);
                        }

                        photoList[counter] = new PhotoModel()
                        {
                            Id      = Guid.NewGuid(),
                            Album   = helper.AlbumId,
                            Title   = newFilename,
                            Date    = DateTime.Now,
                            Preview = $"{helper.Path}prev_{newFilename}",
                            Url     = $"{helper.Path}{newFilename}",
                            Sort    = counter + 1
                        };
                        counter++;
                    }
                }
            }
            if (photoList != null && photoList.Any(a => a != null))
            {
                _cmsRepository.InsertPhotos(helper.AlbumId, photoList);
            }
            return(albumPreview);
        }
Ejemplo n.º 17
0
        public string Import(HttpContext context)//导入数据
        {
            try
            {
                UploadImageHelper uploadBll = new UploadImageHelper();
                context.Response.ContentType = "text/plain";
                HttpPostedFile file     = context.Request.Files["Filedata"];
                string         fileName = file.FileName;
                //string tempPath = AppDomain.CurrentDomain.BaseDirectory + "/UploadFile/" + "SignBook/";  //设置二维码临时位置
                string tempPath = HttpContext.Current.Server.MapPath("~/UploadFile/SignBook/");
                //创建目录
                if (!Directory.Exists(tempPath))
                {
                    Directory.CreateDirectory(tempPath);
                }

                fileName = System.IO.Path.GetFileName(fileName);                  //获取文件名(不带路径)
                string currFileExtension = System.IO.Path.GetExtension(fileName); //获取文件的扩展名
                string currFilePath      = tempPath + fileName;                   //获取上传后的文件路径 记录到前面声明的全局变量
                file.SaveAs(currFilePath);                                        //保存临时文件
                DataTable dt = ExcelToDataTable(fileName, currFilePath);
                for (int r = dt.Rows.Count - 1; r >= 0; r--)
                {
                    DataRow row = dt.Rows[r];
                    if (row["姓名"].ToString().Trim() == "")
                    {
                        row.Delete();
                    }
                }
                dt.AcceptChanges();

                //查询数据库中电话是否存在
                string existMoblie = string.Empty;
                IList <SignBookEntity> entityList = BCtrl_SignBook.Instance.SignBook_GetALL();

                foreach (var item in entityList)
                {
                    string moblie = item.Moblie;
                    foreach (DataRow item2 in dt.Rows)
                    {
                        string moblie2 = item2["手机"].ToString();

                        if (moblie.Trim() == moblie2.Trim())
                        {
                            existMoblie += moblie + ",";
                        }
                    }
                }
                if (!string.IsNullOrEmpty(existMoblie))
                {
                    if (existMoblie.EndsWith(","))
                    {
                        existMoblie = existMoblie.Substring(0, existMoblie.Length - 1);
                        return("false_" + existMoblie);
                    }
                }
                //入库
                foreach (DataRow item in dt.Rows)
                {
                    SignBookEntity entity = new SignBookEntity();
                    entity.Customer    = item["姓名"].ToString().Trim();
                    entity.Moblie      = item["手机"].ToString().Trim().Replace(Environment.NewLine, "");
                    entity.Moblie      = entity.Moblie.Replace("\n", "").Replace("\r", "");
                    entity.Company     = item["单位"].ToString();
                    entity.Department  = item["部门"].ToString();
                    entity.Position    = item["职位"].ToString();
                    entity.Email       = item["邮箱"].ToString();
                    entity.SalesName   = item["业务对接人"].ToString();
                    entity.SignURL     = item["部门"].ToString();
                    entity.CustomerKey = MD5.Fun_MD5(entity.Moblie);
                    entity.LuckyNumber = GetLuckyNumber();
                    entity.CreateTime  = DateTime.Now;
                    entity.IsSign      = 0;

                    //二维码
                    string strName = Guid.NewGuid().ToString("N") + ".png";
                    Bitmap image   = Create_ImgCode(entity.CustomerKey, 15);
                    SaveImg(strName, tempPath, image);

                    //七牛
                    uploadBll.UpLoadImage(tempPath + "/" + strName, out strName, true);
                    entity.SignURL = uploadBll.QiniuDomain + strName;
                    BCtrl_SignBook.Instance.SignBook_Insert(entity);
                }
                File.Delete(currFilePath);
                return("true");
            }
            catch
            {
                return("false");
            }
        }
Ejemplo n.º 18
0
 private async Task OnTapped()
 {
     Image = await UploadImageHelper.UploadImage(Image);
 }
Ejemplo n.º 19
0
        public async Task <IActionResult> UploadImage(UploadImageBindingModel model)
        {
            try
            {
                if (ModelState.IsValid)

                {
                    //get current album name
                    var album = _context.Albums.Where(a => a.Id == model.AlbumId).FirstOrDefault();

                    if (model.UploadImage.Length > 0)
                    {
                        var ext = Path.GetExtension(model.UploadImage.FileName).ToLowerInvariant();

                        if (string.IsNullOrEmpty(ext) || !Constants.permittedExtensions.Contains(ext))
                        {
                            ModelState.AddModelError("InvoiceFile", "Invalid File Type!");
                            return(View());//todo
                        }
                        else

                        {
                            string fileName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0')
                                              + "_" + DateTime.Now.Hour.ToString().PadLeft(2, '0') + DateTime.Now.Minute.ToString().PadLeft(2, '0') + DateTime.Now.Second.ToString().PadLeft(2, '0')
                                              + "_" + DateTime.Now.Millisecond.ToString().PadLeft(4, '0') + ext;

                            string filePath = Path.Combine(_configuration.GetValue <string>("CustomSettings:UploadPath"), album.AlbumFolderName, fileName);

                            using (var stream = System.IO.File.Create(filePath))
                            {
                                await model.UploadImage.CopyToAsync(stream);

                                UploadImageHelper.ResizeAndSaveImage(stream, Path.Combine(_configuration.GetValue <string>("CustomSettings:UploadPath"), album.AlbumFolderName, "thumb", fileName));
                            }


                            StoreImage image = new StoreImage()
                            {
                                AlbumId    = album.Id,
                                Title      = model.Title,
                                FileName   = fileName,
                                UploadDate = DateTime.Now,
                            };

                            _context.StoreImages.Add(image);
                        }
                    }

                    _context.SaveChanges();
                    return(RedirectToAction("Images", "Albums", new { id = album.Id }));
                }
                else
                {
                    return(View(model));
                }
            }

            catch
            {
                throw;
            }
        }
Ejemplo n.º 20
0
        public int SaveEquipment(EquipmentGetRequestModel model)
        {
            var data = model.GetEquipment();

            if (model.PhotoFileData != null)
            {
                if (model != null)
                {
                    if (data.PictureName != null && data.PictureName.Length > 0)
                    {
                        string path = Path.Combine(Environment.CurrentDirectory, "images", data.PictureName);
                        File.Delete(path);
                    }
                }
                data.PictureName = UploadImageHelper.UploadFile(model.PhotoFileData);
            }
            var res = new Equipment
            {
                Id                      = data.Id,
                Title                   = data.Title,
                InventoryNumber         = data.InventoryNumber,
                Destinations            = data.Destinations,
                Year                    = data.Year,
                Zoom                    = data.Zoom,
                PowerVoltage            = data.PowerVoltage,
                SafetyFuses             = data.SafetyFuses,
                AmbientTemperature      = data.AmbientTemperature,
                RelativeHumidity        = data.RelativeHumidity,
                CertificateOfConformity = data.CertificateOfConformity,
                StateCheck              = data.StateCheck,
                Passport                = data.Passport,
                PictureName             = data.PictureName,
                EquipmentStatusId       = data.StatusId
            };

            Db.Equipments.InsertOrUpdate(res);
            Db.Complete();
            try
            {
                var tec    = Db.Equipments.GetTechnicalMaintenancesByEquipmentId(res.Id);
                var empDel = tec.Where(t => !data.TechnicalMaintenances.Select(tm => tm.Id).Contains(t.Id));
                var empIns = data.TechnicalMaintenances.Where(t => !tec.Select(tm => tm.Id).Contains(t.Id));

                Db.EquipmentTechnicalMaintenances.RemoveRange(empDel);

                var tech = data.TechnicalMaintenances != null?
                           data.TechnicalMaintenances.Select(tm => new EquipmentTechnicalMaintenance()
                {
                    Id          = tm.Id,
                    EquipmentId = res.Id,
                    StartDate   = tm.StartDate,
                    EndDate     = tm.EndDate,
                    Description = tm.Description,
                    DescriptionAfterMaintenance = tm.DescriptionAfterMaintenance,
                    ServicePassed = tm.ServicePassed
                }) : null;

                if (tech != null)
                {
                    Db.EquipmentTechnicalMaintenances.InsertOrUpdateRange(tech);
                    Db.Complete();
                }
            }
            catch (Exception e)
            {
                Db.Dispose();
                throw new Exception(e.Message);
            }
            return(res.Id);
        }
Ejemplo n.º 21
0
        public int SaveLaboratory(LaboratoryGetRequesetModel model)
        {
            LaboratoryDataRequesetModel resData = new LaboratoryDataRequesetModel();

            if (model.Data != null)
            {
                resData = model.GetLaboratory();
            }
            else
            {
                throw new Exception("DATA IS NULL");
            }

            if (model != null)
            {
                if (model.LabPhotoFileData != null)
                {
                    if (resData.LaboratoryPhotoName != null)
                    {
                        string path = Path.Combine(Environment.CurrentDirectory, "images", resData.LaboratoryPhotoName);
                        File.Delete(path);
                    }
                    resData.LaboratoryPhotoName = UploadImageHelper.UploadFile(model.LabPhotoFileData);
                }
                if (model.LabPhotoFileData != null)
                {
                    if (resData.LocationPhotoName != null)
                    {
                        string path = Path.Combine(Environment.CurrentDirectory, "images", resData.LocationPhotoName);
                        File.Delete(path);
                    }
                    resData.LocationPhotoName = UploadImageHelper.UploadFile(model.LocationPhotoFileData);
                }
            }

            var labRes = new Laboratory
            {
                Id                  = resData.Id,
                Title               = resData.Title,
                FieldOfStudy        = resData.FieldOfStudy,
                Accreditation       = resData.Accreditation,
                PositionLaboratory  = resData.PositionLaboratory,
                Address             = resData.Address,
                Office              = resData.Office,
                LocationPhotoName   = resData.LocationPhotoName,
                LaboratoryPhotoName = resData.LaboratoryPhotoName,
                DepartmentId        = resData.DepartmentId,
                LaboratoryStatusId  = resData.StatusId,
                DirectorEmployeeId  = resData.DirectorEmployeeId
            };

            Db.Laboratories.InsertOrUpdate(labRes);
            Db.Complete();

            var emp = Db.Laboratories.GetEmployeeByLaboratoryId(labRes.Id);

            if (emp != null)
            {
                var empDel = emp.Where(e => !resData.EmployeeIds.Contains(e.EmployeeId));
                Db.LaboratoryEmployees.RemoveRange(empDel);
            }

            if (resData.EmployeeIds != null && resData.EmployeeIds.Count() > 0)
            {
                var empIns = resData.EmployeeIds.Where(e => !emp.Select(em => em.EmployeeId).Contains(e));
                var empRes = empIns.Select(c => new LaboratoryEmployee()
                {
                    EmployeeId   = c,
                    LaboratoryId = labRes.Id
                });
                Db.LaboratoryEmployees.InsertOrUpdateRange(empRes);
            }

            var eq = Db.Laboratories.GetEqiupmentByLaboratoryId(labRes.Id);

            if (eq != null)
            {
                var eqDel = eq.Where(e => !resData.EqiupmentIds.Contains(e.EquipmentId));
                Db.LaboratoryEqiupments.RemoveRange(eqDel);
            }
            if (resData.EqiupmentIds != null && resData.EqiupmentIds.Count() > 0)
            {
                var eqIns    = resData.EqiupmentIds.Where(e => !eq.Select(em => em.EquipmentId).Contains(e));
                var eqiupRes = eqIns.Select(c => new LaboratoryEqiupment()
                {
                    EquipmentId  = c,
                    LaboratoryId = labRes.Id
                });
                Db.LaboratoryEqiupments.InsertOrUpdateRange(eqiupRes);
            }


            var srv = Db.Laboratories.GetServiceByLaboratoryId(labRes.Id);

            if (srv != null)
            {
                var srvDel = srv.Where(s => !resData.EmployeeIds.Contains(s.Id));
                Db.LaboratoryServices.RemoveRange(srvDel);
            }

            if (resData.Services != null && resData.Services.Count() > 0)
            {
                var serviceRes = resData.Services.Select(c => new EFData.Entity.LaboratoryService()
                {
                    Id         = c.Id,
                    Laboratory = labRes,
                    Title      = c.Title
                });
                Db.LaboratoryServices.InsertOrUpdateRange(serviceRes);
            }


            var lp = Db.Laboratories.GetProjectByLaboratoryId(labRes.Id);

            if (lp != null)
            {
                var lpDel = lp.Where(e => !resData.ProjectIds.Contains(e.ProjectId));
                Db.LaboratoryProjects.RemoveRange(lpDel);
            }
            var lpIns = resData.ProjectIds.Where(e => !lp.Select(q => q.ProjectId).Contains(e));

            if (resData.ProjectIds != null && resData.ProjectIds.Count() > 0)
            {
                var lpRes = lpIns.Select(c => new LaboratoryProject()
                {
                    ProjectId    = c,
                    LaboratoryId = labRes.Id
                });
                Db.LaboratoryProjects.InsertOrUpdateRange(lpRes);
            }

            Db.Complete();
            return(labRes.Id);
        }