Beispiel #1
0
        public async Task <ActionResult> CreateFilterItem(CreateFilterItemViewModel model, HttpPostedFileBase image = null)
        {
            if (ModelState.IsValid)
            {
                var filterItem = Mapper.Map <CreateFilterItemViewModel, FilterItem>(model);
                var filter     = _filterService.GetFilterByValue(model.FilterValue);
                if (filter != null)
                {
                    if (image != null && (image.ContentType == "image/jpeg" || image.ContentType == "image/png"))
                    {
                        string extName  = System.IO.Path.GetExtension(image.FileName);
                        string fileName = $@"{Guid.NewGuid()}{extName}";

                        // сохраняем файл в папку Files в проекте
                        string fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\Content\\Images\\FilterItems", fileName);
                        string urlPath  = Url.Content("~/Content/Images/FilterItems/" + fileName);
                        image.SaveAs(fullPath);
                        Tinify.Key = ConfigurationManager.AppSettings["TINYPNG_APIKEY"];
                        try
                        {
                            using (var s = Tinify.FromFile(fullPath))
                            {
                                var resized = s.Resize(new
                                {
                                    method = "fit",
                                    width  = 100,
                                    height = 70
                                });
                                await resized.ToFile(fullPath);
                            }
                        }
                        catch (System.Exception)
                        {
                            // ignored
                        }
                        filterItem.ImagePath = urlPath;
                    }
                    filterItem.Filter = filter;
                    _filterItemService.CreateFilterItem(filterItem);
                    _filterItemService.SaveFilterItem();
                    return(RedirectToAction("FilterItemList"));
                }
            }
            return(HttpNotFound());
        }