Пример #1
0
        public async Task <IHttpActionResult> uploadFileBase64(CreateImageModel createImageModel)
        {
            var    matches    = Regex.Match(createImageModel.url, @"data:image/(?<type>.+?),(?<data>.+)");
            var    base64Data = matches.Groups["data"].Value;
            String extension  = matches.Groups["type"].Value.Replace(";base64", "");
            var    binData    = Convert.FromBase64String(base64Data);

            String     storagePath = HttpContext.Current.Server.MapPath("~/Assets/IMG/Content");
            String     fileName    = DateTime.Now.Ticks.ToString() + "_" + DateTime.Now.Year + "" + DateTime.Now.Month + "" + DateTime.Now.Day + DateTime.Now.Millisecond + "." + extension;
            String     path        = storagePath + "\\" + fileName;
            var        stream      = new MemoryStream(binData);
            FileStream file        = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
            await stream.CopyToAsync(file);

            Image image = new Image();

            image.productId = createImageModel.productId;
            image.type      = createImageModel.type;
            image.url       = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/assets/img/content/" + fileName;

            Service.imageDAO.insertImage(image);

            Response response = new Response("200", "Ảnh đã được tải lên thành công", image);

            return(Content <Response>(HttpStatusCode.OK, response));
        }
Пример #2
0
        public async Task <IActionResult> CreatAsync(CreateImageModel model)
        {
            var imgForCreate = _mapper.Map <Image>(model);
            var img          = await _imagesService.CreateAsync(imgForCreate);

            return(CreatedAtAction(nameof(GetAsync), new { id = img.Id, }, _mapper.Map <ImageModel>(img)));
        }
Пример #3
0
        public async Task <ImageModel> AddImageToAlbumAsync(CreateImageModel model)
        {
            int   albumId = int.Parse(model.AlbumId);
            Album album   = await db.Albums.FindAsync(albumId);

            if (album == null)
            {
                return(null);
            }

            using (MemoryStream ms = new MemoryStream())
            {
                await model.Image.CopyToAsync(ms);

                Image image = new Image
                {
                    AlbumId = album.Id,
                    Data    = ms.ToArray(),
                    Name    = model.Image.FileName
                };

                await db.Images.AddAsync(image);

                await db.SaveChangesAsync();

                return(mapper.Map <ImageModel>(image));
            }
        }
Пример #4
0
        public async Task <ActionResult <ImageModel> > AddImageToAlbumAsync([FromForm] CreateImageModel model)
        {
            ImageModel image = await imageService.AddImageToAlbumAsync(model);

            if (image == null)
            {
                return(NotFound());
            }

            return(Ok(image));
        }
Пример #5
0
        public async Task <CreateImageResultModel> SaveImage(CreateImageModel model)
        {
            try
            {
                if (model.FileStream.Length > model.MaxFileSize)
                {
                    return(new CreateImageResultModel(false, $"File too large, maximum file size is {model.MaxFileSize.GetBytesReadable()}"));
                }

                var fileName = model.Name;
                if (string.IsNullOrEmpty(fileName))
                {
                    fileName = Path.GetRandomFileName();
                }

                var ext      = string.IsNullOrEmpty(model.Extention) ? ".PNG" : model.Extention;
                var destPath = Path.Combine(model.Directory, fileName) + ext;
                using (var original = System.Drawing.Image.FromStream(model.FileStream))
                {
                    if (!model.CanResize && (original.Width > model.MaxWidth || original.Height > model.MaxHeight))
                    {
                        return(new CreateImageResultModel(false, $"Image too large, maximum image size is {model.MaxWidth} x {model.MaxHeight}"));
                    }

                    if (model.CanResize)
                    {
                        using (var processed = ResizeImage(original, model.MaxWidth, model.MaxHeight, model.PreserveAspectRatio))
                        {
                            processed.Save(destPath);
                        }
                    }
                    else
                    {
                        using (var fileStream = File.Create(destPath))
                        {
                            model.FileStream.Seek(0, SeekOrigin.Begin);
                            await model.FileStream.CopyToAsync(fileStream).ConfigureAwait(false);
                        }
                    }
                }
                return(new CreateImageResultModel
                {
                    Success = true,
                    Name = fileName,
                    Filename = destPath
                });
            }
            catch (Exception)
            {
                return(new CreateImageResultModel(false, "An error occurred saving image file."));
            }
        }
Пример #6
0
        public virtual async Task <IActionResult> Create(CreateImageModel model)
        {
            string        fileName = model.Image.FileName;
            List <string> tags     = SeperateTags(model.Tags);
            string        userId   = User.GetUserId();

            var serviceResult = await service.SaveNewImageAsync(model.CategoryId, model.Description, fileName, userId, tags);

            if (serviceResult.Success)
            {
                await model.Image.SaveImageAsync(environment.GetFullImagesPath(), serviceResult.Result.Url);

                return(RedirectToAction(nameof(Index), model.CategoryId));
            }

            ModelState.FillWithErrors(serviceResult.Errors);
            return(View(model));
        }
Пример #7
0
        public virtual async Task <IActionResult> CreateAjax([FromForm] CreateImageModel model)
        {
            string        fileName = model.Image.FileName;
            List <string> tags     = SeperateTags(model.Tags);
            //string userId = User.GetUserId();
            string userId = "114068491279450791564"; //hardcoded user id

            var serviceResult = await service.SaveNewImageAsync(model.CategoryId, model.Description, fileName, userId, tags);

            if (serviceResult.Success)
            {
                await model.Image.SaveImageAsync(environment.GetFullImagesPath(), serviceResult.Result.Url);

                return(Json(new { success = true, redirectAction = nameof(Index) }));
            }

            return(Json(new { success = false, message = serviceResult.Errors[0] }));
        }
Пример #8
0
        public static CreateImageModel ToCreateFileModel(this IFormFile file, int?imageMaxWidthPx = null,
                                                         int?imageMaxHeightPx = null)
        {
            byte[] imageBytes;

            using (var stream = new MemoryStream())
            {
                file.CopyTo(stream);

                imageBytes = stream.ToArray();
            }

            var createFileModel = new CreateImageModel
            {
                Name = file.FileName,
                ImageContentBase64 = Convert.ToBase64String(imageBytes),
                ImageMaxWidthPx    = imageMaxWidthPx,
                ImageMaxHeightPx   = imageMaxHeightPx
            };

            return(createFileModel);
        }
Пример #9
0
        public async Task <ActionResult> CreateImage([Bind(Include = "group")] CreateImageModel model)
        {
            ActionResult result = null;

            byte[] buffer = null;

            if (Request.Files.Count.Equals(1))
            {
                model.Name = Request.Files[0].FileName;

                buffer = new byte[Request.Files[0].ContentLength];

                using (var reader = new StreamReader(Request.Files[0].InputStream))
                {
                    reader.BaseStream.Read(buffer, 0, Request.Files[0].ContentLength);
                }
            }

            await Image.CreateImage(model.Name, model.Group, buffer);

            result = RedirectToAction("Index");

            return(result);
        }
Пример #10
0
        public async Task <IHttpActionResult> insertNewProduct([FromBody] CreateProductModel createProductModel)
        {
            Response        response    = Utils.checkInput(createProductModel, CreateProductModel.required);
            String          accessToken = HttpContext.Current.Request.Headers.Get("Authorization").Replace("Bearer ", "");
            Token           token       = Service.tokenDAO.getByAccessToken(accessToken);
            ApplicationUser appUser     = Service._userManager.FindByEmailAsync(token.userName).Result;

            createProductModel.createdBy = appUser.userInfoId;
            if (response.code != "422")
            {
                Product  productcheck = Service.productDAO.checkexist(createProductModel.code);
                UserInfo user         = Service.userInfoDAO.getUserInfo(createProductModel.createdBy);
                if (user == null)
                {
                    response.code   = "404";
                    response.status = "Người dùng hiện tại chưa có quyền thêm sản phẩm";
                    return(Content <Response>(HttpStatusCode.NotFound, response));
                }
                else if (productcheck != null)
                {
                    response.code   = "409";
                    response.status = "Trùng sản phẩm, xin nhập lại";
                    return(Content <Response>(HttpStatusCode.Conflict, response));
                }
                else
                {
                    //create Product object to insert data
                    Product product = new Product();
                    product.code             = createProductModel.code;
                    product.shortDescription = createProductModel.shortDescription;
                    product.longDescription  = createProductModel.longDescription;
                    product.name             = createProductModel.name;
                    product.createdBy        = createProductModel.createdBy;
                    Service.productDAO.insertProduct(product);

                    //insert data to category product
                    Product newProduct = Service.productDAO.checkexist(product.code);
                    for (int i = 0; i < createProductModel.categories.Length; i++)
                    {
                        if (Service.categoryDAO.checkExist(createProductModel.categories[i]) != null)
                        {
                            CategoryProduct catepro = new CategoryProduct();
                            catepro.categoryId = createProductModel.categories[i];
                            catepro.productId  = newProduct.id;
                            Service.categoryProductDAO.insertCategoryProduct(catepro);
                        }
                    }
                    foreach (var attribute in createProductModel.attributes)
                    {
                        ProductAttribute productAttribute = new ProductAttribute(product.id, attribute.Key, attribute.Value.ToString());
                        Service.productAttributeDAO.insertProductAttribute(productAttribute);
                    }

                    foreach (var thumbnail in createProductModel.thumbnails)
                    {
                        HttpClient httpClient = new HttpClient();
                        httpClient.BaseAddress = baseUrl;
                        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        httpClient.DefaultRequestHeaders.Add("Authorization", accessToken);

                        CreateImageModel createImageModel = new CreateImageModel();
                        createImageModel.productId = product.id;
                        createImageModel.url       = thumbnail.GetValue("url").ToString();
                        createImageModel.type      = "thumbnail";

                        HttpContent httpContent = new ObjectContent <CreateImageModel>(createImageModel, new JsonMediaTypeFormatter());
                        await httpClient.PostAsync("api/image/upload/base64", httpContent);
                    }

                    foreach (var detail in createProductModel.details)
                    {
                        HttpClient httpClient = new HttpClient();
                        httpClient.BaseAddress = baseUrl;
                        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        httpClient.DefaultRequestHeaders.Add("Authorization", accessToken);

                        CreateImageModel createImageModel = new CreateImageModel();
                        createImageModel.productId = product.id;
                        createImageModel.url       = detail.GetValue("url").ToString();
                        createImageModel.type      = "detail";

                        HttpContent httpContent = new ObjectContent <CreateImageModel>(createImageModel, new JsonMediaTypeFormatter());
                        await httpClient.PostAsync("api/image/upload/base64", httpContent);
                    }

                    response.code    = "201";
                    response.status  = "Thêm sản phẩm thành công";
                    response.results = product;
                    return(Content <Response>(HttpStatusCode.Created, response));
                }
            }

            return(Content <Response>(HttpStatusCode.OK, response));
        }